Skip to the page

Java concurrency · Build it

Print odd and even numbers with two threads

The interviewer asks

Write a Java program with two threads: one prints odd numbers and the other prints even numbers, so that together they print 1 to 20 in order.

Then

Follow-ups the interviewer asks next

  1. Why check the turn in a while loop and not an if?
  2. What happens if you call notify() without holding the lock?
  3. notify or notifyAll here?
  4. Can you do it with Semaphores, or with ReentrantLock and Condition?
  5. Now three threads printing 1, 2, 3, 1, 2, 3 in turn.

The answer

What a strong answer covers

  • A shared lock and counter. Each thread loops: take the lock; while numbers remain and it isn't its turn (counter % 2 doesn't match), lock.wait(); if numbers remain, print and increment; then lock.notifyAll() and release the lock. Stop when the counter passes 20.
  • while, not if: spurious wakeups, and waking when it isn't your turn.
  • wait and notify need the monitor held, or they throw IllegalMonitorStateException; wait releases the lock while waiting.
  • Clean finish: the last thread notifies so the other doesn't wait forever; main joins both; InterruptedException restores the interrupt flag.
  • Semaphore version (cleanest): odd starts with 1 permit, even with 0; each acquires its own, prints, releases the other's.
  • ReentrantLock with one Condition per thread, signalling exactly the next one; the same idea scales to three threads (turn = counter % 3).

The red pen

Common traps

Avoid:Thread.sleep to "order" output; if instead of while; a program that hangs at the end.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview