Join overview

  • Eclipse: Oxygen
  • Java: 1.8

Join overview

The joining method is an optimal solution to the problem of inconsistency that occurs due to threads not having a proper order. The join method is used to notify that the thread will wait until the execution of the given thread before execution.

Here we have started the two threads in a sequential manner the thread scheduler does not start and end them in the specified order. Every time you execute this code, you may get a different result.

Output

The value of counter: 1897

To executes the treads in a specified order. We will make use of join() method.

In the following program, we can see clearly thread2 starts after thread1 is finished execution, and the main thread will start its execution after thread2 is finished execution.

Output

The value of counter: 2000

There are three versions of the join.

  1. join () method will put the current thread on wait until the thread in which it is called is dead. If the thread is interrupted, InterruptedException will be thrown.
  2. join (long millis) method will put the current thread on wait until the thread in which it is called is dead or wait for the specified time (milliseconds).
  3. join (long millis, int nanos) method will put the current thread on wait until the thread in which it is called is dead or wait for the specified time (milliseconds + nanos).

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu