Similar Problems

Similar Problems not available

Print In Order - Leetcode Solution

Companies:

LeetCode:  Print In Order Leetcode Solution

Difficulty: Unknown

Topics: unknown  

Problem Statement:

Suppose we have a class:

public class Foo {
    public void first() { ... }
    public void second() { ... }
    public void third() { ... }
}

The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().

Solution:

To solve this problem, we will use CountDownLatch which is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. We will use two CountDownLatch instances to ensure that second() is executed after first() and third() is executed after second().

In the first latch, we will count down from 1 to 0 to release the second thread and in the second latch, we will count down from 2 to 0 to release the third thread.

The solution will look like this:

import java.util.concurrent.CountDownLatch;

public class Foo {
    private final CountDownLatch latch1;
    private final CountDownLatch latch2;
    
    public Foo() {
        latch1 = new CountDownLatch(1);
        latch2 = new CountDownLatch(1);
    }
    
    public void first(Runnable printFirst) {
        printFirst.run();
        latch1.countDown();
    }
    
    public void second(Runnable printSecond) throws InterruptedException {
        latch1.await();
        printSecond.run();
        latch2.countDown();
    }
    
    public void third(Runnable printThird) throws InterruptedException {
        latch2.await();
        printThird.run();
    }
}

We have used three runnables for each method that will perform their respective tasks.

In the first method, printFirst will be executed first, and then we will count down the first latch to release the second thread.

In the second method, we will wait for the first latch to be released, which will ensure that the first method has been called and printed its output. Then printSecond will print its output, and we will count down the second latch to release the third thread.

In the third method, we will wait for the second latch to be released, ensuring that both first and second methods have been called and printed their output before printThird is executed.

This will ensure that the output is printed in the order of first(), second(), and third(), irrespective of the order in which the threads are executed.

I hope this explanation helps!

Print In Order Solution Code

1