Print Zero Even Odd

Medium
ConcurrencySemaphoreThread 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 prints 0 before 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

  1. Output must strictly follow pattern: 0, number, 0, number, ... alternating.
  2. zero() must precede every number.
  3. Even numbers go to Thread B, odd numbers to Thread C.
  4. 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.