Search code examples
javamultithreadingsynchronizationjava.util.concurrent

Synchronizing three steps in three different threads?


In my main programme, i start three threads as described below

Thread 1:- having steps 1A and 1B

Thread 2:- having steps 2A and 2B

Thread 3:- having steps 3A and 3B

I want Thread 1, 2 and 3 proceed for their next step only when all of them complete their first step.

For example:- Thread 2 and Thread 3 have completed their first steps i.e 2A and 3A respectively but Thread1 did not complete step 1A. So thread 2 and 3 will wait till thread 1 complete step 1A

I know i can handle it with simple static counter and only proceed once counter value is 3. But i am sure there must be something off the shelve available in thread/java.util.concurrent package?


Solution

  • Use a java.util.concurrent.CyclicBarrier. For example, create a CyclicBarrier with a count of 3:

    CyclicBarrier cb = new CyclicBarrier(3);
    new Thread(new Thread1(cb)).start();
    new Thread(new Thread2(cb)).start();
    new Thread(new Thread3(cb)).start();
    
    class Thread1 implements Runnable() {
       private CyclicBarrier barrier;
       public Thread1(CyclicBarrier cb) {
          barrier = cb;
       }
    
       public void run() {
           // execute 1A
           barrier.await();
           // execute 1B
    }
    
    class Thread2 implements Runnable() {
       private CyclicBarrier barrier;
       public Thread2(CyclicBarrier cb) {
          barrier = cb;
       }
    
       public void run() {
           // execute 2A
           barrier.await();
           // execute 2B
    }
    
    // repeat for Thread3
    

    Each thread will execute until it reach the await() call, then it will stop until all 3 threads have reached that rendezvous point. When the third thread reaches that point (whichever one it is), the two that were waiting will proceed.