The problem
Three methods named first, second, and third are each invoked on a separate thread in an arbitrary order by the runtime. Your job is to guarantee the side effects happen in the sequence first then second then third regardless of how the threads are scheduled.
The ordering tool
This is a pure happens before ordering problem with no shared mutable data beyond the sequencing. The classic tools are two semaphores or two latches:
- A gate between first and second starts closed.
- A gate between second and third starts closed.
- first runs, then opens the first gate.
- second waits on the first gate, runs, then opens the second gate.
- third waits on the second gate, then runs.
Why semaphores fit
A semaphore initialised to zero blocks a waiter until someone posts it. That is exactly a one shot signal saying the previous step finished. The pattern chains these signals to force a total order across unrelated threads.
Key idea
Print in order chains two zero initialised semaphores so each method waits for the previous one to signal, forcing first then second then third.