Problem 9 Print in Order using multithreading
Problem Statement
Ensure the ordered execution of methods across different threads. We have three methods — first(), second(), and third() — and we must guarantee that first() completes before second(), and second() completes before third(), regardless of the order in which the threads are started or scheduled.
Solution
We use two CountDownLatch objects as one-shot signals between threads. A CountDownLatch initialized to 1 blocks any thread that calls await() until another thread calls countDown().
firstDonestarts at 1.second()waits on it;first()counts it down after printing.secondDonestarts at 1.third()waits on it;second()counts it down after printing.
This is a minimal-change, coherent design: even if the JVM schedules third() before first(), the latch forces third() to wait until second() has run, and second() waits until first() has run.
Trace
- Thread A starts
first(), prints "first", and callsfirstDone.countDown(). - Thread B, blocked in
firstDone.await(), unblocks, prints "second", and callssecondDone.countDown(). - Thread C, blocked in
secondDone.await(), unblocks and prints "third".
Code
import java.util.concurrent.CountDownLatch;
/**
* This Foo class ensures that its methods are called in a specific order:
* `first`, followed by `second`, and then `third`.
*/
public class Solution {
// CountDownLatches are synchronization aids that allow one or more threads to wait
// until a set of operations being performed in other threads completes.
// This latch ensures that `second` waits until `first` has finished executing.
private final CountDownLatch firstDone = new CountDownLatch(1);
// This latch ensures that `third` waits until `second` has finished executing.
private final CountDownLatch secondDone = new CountDownLatch(1);
public Solution() {}
public void first() {
// This is the first method, and it can proceed without waiting.
print("first");
// Decrement the count of the latch, signaling that this method is done.
firstDone.countDown();
}
public void second() throws InterruptedException {
// Wait for the first method to complete.
firstDone.await();
print("second");
// Signal that the second method has now completed.
secondDone.countDown();
}
public void third() throws InterruptedException {
// Wait for the second method to complete.
secondDone.await();
print("third");
}
private void print(String msg) {
System.out.print(msg);
}
public static void main(String[] args) {
Solution foo = new Solution();
Thread threadA = new Thread(() -> {
try {
foo.first();
} catch (Exception e) {
e.printStackTrace();
}
});
Thread threadB = new Thread(() -> {
try {
foo.second();
} catch (Exception e) {
e.printStackTrace();
}
});
Thread threadC = new Thread(() -> {
try {
foo.third();
} catch (Exception e) {
e.printStackTrace();
}
});
// The actual order in which the threads start and get scheduled is up to the
// JVM and the OS, but the CountDownLatches ensure they complete as first,
// second, third.
threadA.start();
threadB.start();
threadC.start();
}
}
Time Complexity
O(1) per method call. await() blocks until the corresponding signal, but does no extra work.
Space Complexity
O(1) — only two latch objects are allocated.
Takeaways
- Use a one-shot synchronization aid when the ordering requirement is "wait for step N, then signal step N+1."
CountDownLatchis a clean fit here because each transition happens exactly once.- Always start the threads; the latches guarantee completion order even if startup order is different.
Problem and solution structure adapted from DesignGurus. Re-authored and corrected for this guide.
🤖 Don't fully get this? Learn it with Claude
Stuck on Problem 9 Print in Order using multithreading? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Problem 9 Print in Order using multithreading** (Concurrency). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Problem 9 Print in Order using multithreading** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Problem 9 Print in Order using multithreading**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Problem 9 Print in Order using multithreading**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.