Three threads T1, T2, and T3

Three threads T1, T2, and T3

To ensure a specific sequence of execution among multiple threads in Java, you can utilize various synchronization mechanisms such as wait() and notify(), CountDownLatch, CyclicBarrier, or Semaphore. Here, I’ll demonstrate how to achieve the sequence T1, T2, T3 using CountDownLatch.

Three threads T1, T2, and T3

Explanation

  • CountDownLatch is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
  • We can create three CountDownLatch instances, each representing the completion of one thread’s execution.
  • Thread T1 will execute its task and then count down the latch for T2.
  • Thread T2 will execute its task and then count down the latch for T3.
  • Thread T3 will execute its task.
  • By using await() and countDown() methods of CountDownLatch, we can ensure the required sequence of execution.

Example
java
import java.util.concurrent.CountDownLatch;

public class ThreadSequenceExample {
    public static void main(String[] args) {
        CountDownLatch latchT1 = new CountDownLatch(1);
        CountDownLatch latchT2 = new CountDownLatch(1);

        Thread t1 = new Thread(() -> {
            // Task for Thread T1
            System.out.println("Thread T1 is executing");
            // Count down the latch for Thread T2
            latchT2.countDown();
        });

        Thread t2 = new Thread(() -> {
            try {
                // Wait until Thread T1 completes
                latchT2.await();
                // Task for Thread T2
                System.out.println("Thread T2 is executing");
                // Count down the latch for Thread T3
                latchT1.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t3 = new Thread(() -> {
            try {
                // Wait until Thread T2 completes
                latchT1.await();
                // Task for Thread T3
                System.out.println("Thread T3 is executing");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // Start the threads
        t1.start();
        t2.start();
        t3.start();
    }
}

Three threads T1, T2, and T3 Example

In this example, Thread T1 executes its task first, then it counts down the latch for Thread T2. Thread T2 waits until Thread T1 completes its task, then executes its own task and counts down the latch for Thread T3. Finally, Thread T3 waits until Thread T2 completes its task and executes its own task. Thus, we ensure the sequence T1, T2, T3

Homepage

Readmore