[Note: I cannot understand join () when I am new to multithreading. Function You have read all three books. After some experiments, I finally figured out the essence of join. Let's take a look at whether my writing method is easy to understand, whether it really writes the essence of join (), and give more valuable comments.]
Join () of the thread class () Method Merge two threads that run alternately into the threads that run sequentially. For example, if the join () method of thread a is called in thread B, thread a will continue to execute thread B until thread a completes execution.
Try: thread insertion
// C # beginner Classroom "
// Add a namespace
Using system. Threading;
Static void main (string [] ARGs)
{
// Thread
Thread ThreadA = new Thread (delegate ()
{
For (int I = 0; I <= 100000000; I ++)
{
If (I % 1000000 = 0)
{
Console. Write ('A ');
}
}
});
// Thread B
Thread ThreadB = new Thread (delegate ()
{
For (int I = 0; I <= 50000000; I ++)
{
If (I % 1000000 = 0)
{
Console. Write ('B ');
}
}
// Insert thread A here
ThreadA. Join ();
For (int I = 0; I <= 50000000; I ++)
{
If (I % 1000000 = 0)
{
Console. Write ('B ');
}
}
});
// Start the thread
Threada. Start ();
Threadb. Start ();
}
The running result is as follows: Analysis Do you know why?
The running results show that the first two threads alternate. Proceed When thread B executes the statement "threada. "Join ()", before thread a is inserted into thread B, the two threads are merged together and executed sequentially until all the statements in thread a are executed, to execute the remaining statement in thread B.
In other words, when we call threada. Join () in thread B, this method will be returned only after the thread threada completes execution. The join () function can also accept Indicates The number of milliseconds. After the specified time is reached, if thread A is not running, the join function will return. At this time, thread a and thread B are in the alternating state again.
Http://www.cnblogs.com/millen/archive/2009/09/07/1520353.html