An example of the use of the join method in Java multithreaded programming

  • 2020-04-01 02:50:26
  • 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 int n = 0;
static synchronized void inc()
{
n++;
}
public void run()
{
for (int i = 0; i < 10; i++)
try
{
inc();
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 routines 2-8, 100 threads are created, each increasing the static variable n by 10. If you output n after all 100 threads have executed, the value of n should be 1000.
1.   Test 1
Run the above program with the following command:


java mythread.JoinThread

The results of the program are as follows:

n=442

This might be a little bit different in different environments, but in general n is not going to be equal to 1000. From the above result, we can be sure that the n is output before the 100 threads are finished 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:


n=1000

Run the above command in any running environment and you get the same result: n=1000. That's a pretty good indication that these 100 threads must have run out, so n must be equal to 1000.


Related articles: