In the preceding example, the join method of the Thread class is used multiple times. I think you may have guessed what the function of the join method is. Yes, the function of the join method is to convert the asynchronous thread into synchronous execution. That is to say, after the start method of the thread instance is called, this method will return immediately. If a value calculated by this thread needs to be used after the start method is called, you must use the join method. If the join method is not used, it cannot be guaranteed that the thread will be executed completely when a statement following the start method is executed. After the join method is used, the program will not execute until the thread exits.
The following code demonstrates join usage.
Copy codeThe Code is as follows: package mythread;
Public class JoinThread extends Thread
{
Public static volatile int n = 0;
Public void run ()
{
For (int I = 0; I <10; I ++, n ++)
Try
{
Sleep (3); // delay of 3 ms to make running results more random
}
Catch (Exception e)
{
}
}
Public static void main (String [] args) throws Exception
{
Thread threads [] = new Thread [100];
For (int I = 0; I <threads. length; I ++) // create 100 threads
Threads [I] = new JoinThread ();
For (int I = 0; I <threads. length; I ++) // run the first 100 threads just created.
Threads [I]. start ();
If (args. length> 0)
For (int I = 0; I <threads. length; I ++) // continue after all the 100 threads are executed
Threads [I]. join ();
System. out. println ("n =" + JoinThread. n );
}
}
100 threads are created in the 2-8 routine, and each thread increases the static variable n by 10. If n is output after all the 100 threads are executed, the n value should be 1000.
1. Test 1
Run the above program using the following command:
Copy codeThe Code is as follows: 1 java mythread. JoinThread
The program running result is as follows:Copy codeThe Code is as follows: 1 n = 442
The running result may be different in different running environments, but n is not equal to 1000. from the above results, we can be sure that n will be output if the 100 threads are not all executed.
2. Test 2
Run the preceding code using the following command:
In the preceding command line, there is a join parameter. In fact, any parameter can be used in the command line, as long as there is a parameter. join is used here, only to indicate that the join method is used for Synchronous execution of the 100 threads.
The program running result is as follows:
Copy codeThe Code is as follows: 1 n = 1000
Regardless of the running environment, the above command will get the same result: n = 1000. this fully demonstrates that all the 100 threads have been executed. Therefore, n must be equal to 1000.