A classic multi-thread learning code.
1. multithreading synchronization is used.
2. multithreading sequence is used.
If you are interested, read the following code carefully. Pay attention to the sequence of code segments and think about whether the order of these codes can be exchanged. Why? This should be very helpful for learning. For demonstration, it takes some time for all threads to Sleep.
Using System. Net;
Using System;
Using System. IO;
Using System. Text;
Using System. Threading;
Using System. Diagnostics;
Namespace Webb. Study
{
Class TestThread
{
Static Mutex m_Mutex = new Mutex ();
Static Thread [] m_testThreads = new Thread [10];
Static int m_threadIndex = 0;
Static void ThreadCallBack ()
{
TestThread. m_Mutex.WaitOne ();
Int m_index = m_threadIndex;
TestThread. m_Mutex.ReleaseMutex ();
Console. WriteLine ("Thread {0} start.", m_index );
For (int I = 0; I <= 10; I ++)
{
TestThread. m_Mutex.WaitOne ();
Console. WriteLine ("Thread {0}: is running. {1}", m_index, I );
TestThread. m_Mutex.ReleaseMutex ();
Thread. Sleep (100 );
}
Console. WriteLine ("Thread {0} end.", m_index );
}
Public static void Main (String [] args)
{
Console. WriteLine ("Main thread start .");
For (int I = 0; I <TestThread. m_testThreads.Length; I ++)
{
TestThread. m_threadIndex = I;
TestThread. m_testThreads [I] = new Thread (new ThreadStart (ThreadCallBack ));
TestThread. m_testThreads [I]. Start ();
Thread. Sleep (100 );
}
For (int I = 0; I <TestThread. m_testThreads.Length; I ++)
{
TestThread. m_testThreads [I]. Join ();
}
Console. WriteLine ("Main thread exit .");
}
}
}
1. Can these two sentences in the main function be exchanged? Why?
TestThread. m_testThreads [I]. Start ();
Thread. Sleep (100 );
2. Can the two sentences in the CallBack function be exchanged? Why? What are the different results?
TestThread. m_Mutex.ReleaseMutex ();
Thread. Sleep (100 );
3. Can the main function be written like this? Why? What are the different results?
Public static void Main (String [] args)
{
Console. WriteLine ("Main thread start .");
For (int I = 0; I <TestThread. m_testThreads.Length; I ++)
{
TestThread. m_threadIndex = I;
TestThread. m_testThreads [I] = new Thread (new ThreadStart (ThreadCallBack ));
TestThread. m_testThreads [I]. Start ();
TestThread. m_testThreads [I]. Join ();
Thread. Sleep (100 );
}
Console. WriteLine ("Main thread exit .");
}
4. What are the functions of these statements? What problems do programs have? What should I do?
TestThread. m_Mutex.WaitOne ();
Int m_index = m_threadIndex;
TestThread. m_Mutex.ReleaseMutex ();
Only for study and discussion.