Print in Order - Problem

Suppose we have a class with three methods that print specific messages:

public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}

The same instance of Foo will be passed to three different threads:

  • Thread A will call first()
  • Thread B will call second()
  • Thread C will call third()

Design a mechanism to ensure that second() is executed after first(), and third() is executed after second(), regardless of thread scheduling order.

Note: We do not know how the threads will be scheduled by the operating system. The input format ensures comprehensive testing of your synchronization mechanism.

Input & Output

Example 1 — Standard Execution
$ Input: n = 1
Output: firstsecondthird
💡 Note: Thread A executes first(), signals Thread B to execute second(), which then signals Thread C to execute third(). The output is always in the correct order regardless of thread scheduling.
Example 2 — Different Thread Start Order
$ Input: n = 1
Output: firstsecondthird
💡 Note: Even if Thread C starts first, it must wait for Thread B. Thread B must wait for Thread A. The synchronization ensures the output is always firstsecondthird.
Example 3 — Concurrent Start
$ Input: n = 1
Output: firstsecondthird
💡 Note: All threads start simultaneously, but synchronization primitives ensure first() completes before second(), and second() before third().

Constraints

  • The same instance of Foo will be passed to three different threads
  • Thread A will call first()
  • Thread B will call second()
  • Thread C will call third()
  • We cannot control thread scheduling order

Visualization

Tap to expand
Print in Order: Thread Synchronization ChallengeThread AThread BThread Cfirst()second()third()Can start anytimeMust wait for AMust wait for BSynchronizationMechanismExecution Order: A → B → COutput: firstsecondthirdRegardless of thread start order, output is always consistent
Understanding the Visualization
1
Input
Three threads A, B, C ready to execute
2
Synchronization
Coordination ensures proper execution order
3
Output
Always produces 'firstsecondthird'
Key Takeaway
🎯 Key Insight: Thread synchronization primitives ensure execution order despite unpredictable scheduling
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen