Print Zero Even Odd
MediumConcurrencySemaphoreThread CoordinationMutex
Problem Statement
Design a thread-safe class ZeroEvenOdd where three threads cooperate to output the sequence "010203040506..." up to n.
- Thread A calls
zero()— always prints0before each number. - Thread B calls
even()— prints even numbers. - Thread C calls
odd()— prints odd numbers.
The output for n = 5 is "0102030405".
class ZeroEvenOdd {
private int n;
public ZeroEvenOdd(int n) { this.n = n; }
public void zero(IntConsumer printNumber) throws InterruptedException {}
public void even(IntConsumer printNumber) throws InterruptedException {}
public void odd(IntConsumer printNumber) throws InterruptedException {}
}
Key Entities
- ZeroEvenOdd: Maintains shared counter and synchronization state.
- Three semaphores:
zeroSem(starts at 1),oddSem(starts at 0),evenSem(starts at 0). - Coordination logic: zero() decides whether to signal odd or even based on the current number.
Requirements
- Output must strictly follow pattern: 0, number, 0, number, ... alternating.
- zero() must precede every number.
- Even numbers go to Thread B, odd numbers to Thread C.
- No busy-waiting.
Asked at: Goldman Sachs, Amazon, Microsoft, Google
!Constraints
- 1 ≤ n ≤ 1000
- Exactly three threads, each calling only their assigned method.
- Output length is exactly 2n.
- No Thread.sleep() based synchronization.
Output
Run or submit your code to see output here.