Introduction to the use of join method for Java threads

  • 2020-04-01 01:49:42
  • OfStack

The join method of the Thread class is used several times in the above example. I think you've probably guessed what the join method does. Yes, what the join method does is make asynchronous threads execute synchronously. That is, when the start method of the thread instance is called, the method returns immediately, and if a value calculated by the thread is needed after the start method is called, the join method must be used. If you do not use the join method, there is no guarantee that the thread will finish executing when a statement following the start method is executed. With the join method, the program does not execute until the thread exits.
The following code demonstrates the use of join.


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);  //To make the results more random, delay by 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 you just created
             threads[i].start();
         if (args.length > 0)  
             for (int i = 0; i < threads.length; i++)   //Continue after all 100 threads have 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 have executed, the value of n should be 1000.

      1.   Test 1

      Run the above program with the following command:


1 java mythread.JoinThread

The results of the program are as follows:

1 n=442

The result of this run may be different in different running environments, but generally n is not equal to 1000. From the above results, we can be sure that n is output before all the 100 threads finish executing.

      2.   Test 2

      Run the above code using the following command:

      There is a parameter join on the command line above, and you can use any parameter on the command line, as long as there is a parameter, so you use a join here, just to indicate that you want to use the join method to synchronize the execution of the 100 threads.

      The results of the program are as follows:


1 n=1000

Running the above command in any running environment gives the same result: n=1000. This fully demonstrates that the 100 threads must have executed, so n must be equal to 1000.


Related articles: