In the above example, the join method of the Thread class is used many times. I think you may have guessed what the function of the join method is. Yes, the function of the join method is to turn the asynchronous execution thread into a synchronous execution. That is to say, when the start method of the thread instance is called, this method will return immediately. If you need to use a value calculated by this thread after calling the start method, you must use the join method. If you do not use the join method, there is no guarantee that when a statement following the start method is executed, the thread will be executed. After using the join method, the program will not continue execution until this thread exits. The following code demonstrates the use of join.
Copy the code code as follows:
package mythread;
public class JoinThread extends Thread
{
public static int n = 0;
static synchronized void inc()
{
n++;
}
public void run()
{
for (int i = 0; i < 10; i++)
try
{
inc();
sleep(3); // In order to make the running results more random, delay 3 milliseconds
}
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 100 threads just created
threads[i].start();
if (args. length > 0)
for (int i = 0; i < threads.length; i++) // Continue after all 100 threads have been executed
threads[i].join();
System.out.println("n=" + JoinThread.n);
}
}
In routine 2-8, 100 threads are created, and each thread increases the static variable n by 10. If n is output after all 100 threads are executed, the n value should be 1000.
1. Test 1
Use the following command to run the above program:
Copy the code code as follows:
java mythread.JoinThread
The results of running the program are as follows:
Copy the code code as follows:
n=442
This running result may have some differences under different running environments, but generally n will not equal 1000. From the above results, we can be sure that n is not output after all 100 threads have been executed.
2. Test 2
Run the above code using the following command:
There is a parameter join in the above command line. In fact, any parameter can be used in the command line, as long as there is one parameter. Join is used here just to indicate that the join method is used to synchronize the execution of these 100 threads.
The results of running the program are as follows:
Copy the code code as follows:
n=1000
No matter what operating environment you run the above command, you will get the same result: n=1000. This fully demonstrates that all 100 threads must have been executed, therefore, n must be equal to 1000.