Two latches
Time O(1) Space O(1)firstDone and secondDone latches; second awaits firstDone, third awaits secondDone. Start threads in the given order, join all, return the buffer.
import java.util.*;
import java.util.concurrent.CountDownLatch;
class Solution {
public String printInOrder(int[] order) throws InterruptedException {
StringBuffer out = new StringBuffer(); // thread-safe appends
CountDownLatch firstDone = new CountDownLatch(1), secondDone = new CountDownLatch(1);
Runnable[] jobs = {
() -> { out.append("first"); firstDone.countDown(); },
() -> { await(firstDone); out.append("second"); secondDone.countDown(); },
() -> { await(secondDone); out.append("third"); },
};
List<Thread> threads = new ArrayList<>();
for (int k : order) {
Thread t = new Thread(jobs[k - 1]);
threads.add(t);
t.start();
}
for (Thread t : threads) t.join();
return out.toString();
}
private static void await(CountDownLatch latch) {
try { latch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}Verdict: Latches are made for "wait until X happened".