Quick revision
The short answer
Both threads share an int next = 1 guarded by one lock object, and each loops while next <= 10. Inside synchronized (lock), a thread waits with while (next % 2 != myParity && next <= 10) lock.wait(); then prints next, increments it and calls lock.notifyAll() so the other thread can check its turn. The wait must be in a while loop, not an if, because a thread can wake up spuriously, without any notify, and because notifyAll wakes threads whose condition may still be false, so each thread must recheck before acting. Semaphores handing a permit back and forth, or a ReentrantLock with Conditions, are alternatives, and the main thread joins both workers and restores the interrupt flag if it is interrupted.
What to remember
In this answer, we made two threads take turns with one lock and a shared counter: each thread waits inside synchronized while next does not have its parity, then prints, increments and calls notifyAll. The wait sits in a while loop because of spurious wakeups and because notifyAll wakes threads whose condition may still be false, and the extra next <= 10 check lets the last waiting thread exit. Two semaphores handing a permit back and forth, or a ReentrantLock with one Condition per thread, are cleaner alternatives, and the main thread joins both workers while workers restore the interrupt flag.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Both threads share an int next = 1 guarded by one lock object, and each loops while next <= 10. Inside synchronized (lock), a thread waits with while (next % 2 != myParity && next <= 10) lock.wait(); then prints next, increments it and calls lock.notifyAll() so the other thread can check its turn. The wait must be in a while loop, not an if, because a thread can wake up spuriously, without any notify, and because notifyAll wakes threads whose condition may still be false, so each thread must recheck before acting. Semaphores handing a permit back and forth, or a ReentrantLock with Conditions, are alternatives, and the main thread joins both workers and restores the interrupt flag if it is interrupted.
Why this question is asked
Printing odd and even numbers from two threads is a toy, but the pattern inside it, threads taking turns based on shared state, is the core of producer-consumer queues, pipelines and any hand-off between threads. Interviewers use it to check that we understand what wait and notify really do, why they need the lock, and why the wait condition goes in a loop. Getting it slightly wrong produces output that is right most of the time and hangs or misorders occasionally. In this answer, we will recap the monitor methods, write the solution with a shared lock, trace how the two threads hand over, explain the while loop, and look at the Semaphore and Condition alternatives and at clean shutdown.
1A Quick Recap of wait and notifyAll
Every Java object can act as a monitor. synchronized (lock) lets one thread at a time run the block. Inside it, lock.wait() does two things atomically: it releases the lock and puts the thread to sleep until another thread calls lock.notify() or lock.notifyAll(). When the sleeping thread wakes, it must reacquire the lock before wait() returns, so it continues inside the synchronized block again.
notify() wakes one waiting thread chosen by the JVM, and notifyAll() wakes all of them; they then compete for the lock one at a time. Calling wait or notify without holding the lock throws IllegalMonitorStateException, because the condition they protect must be checked and changed under the same lock.
2The Solution With a Shared Lock
The shared state is one counter. Each thread knows its parity, 1 for odd and 0 for even, and may only print when next has that parity.
9 messages in order. Play them, or step through them one at a time.
Each thread prints only after rechecking next while holding the lock.
Notice the two checks of next <= MAX. The outer loop stops a thread after the last number. The inner condition and the if after it handle the last hand-over: after the odd thread prints 9, it waits for its next turn; the even thread prints 10, sets next to 11 and calls notifyAll; the odd thread wakes, sees next > MAX and leaves instead of waiting forever. Without that check, the odd thread would hang and join would never return.
The order of starting the threads does not matter. If the even thread runs first, it sees next = 1, which is odd, and waits, releasing the lock so the odd thread can begin.
3Why the Wait Must Be in a Loop
There are two reasons, and both mean that waking up does not prove that it is our turn. The first is spurious wakeups: the Java specification allows wait() to return without any notify, because some operating systems' thread primitives behave that way, and the JVM does not hide it. If we wrote if instead of while, a spurious wakeup of the even thread while next = 3 would make it print 3.
The second reason is notifyAll itself. It wakes every waiting thread, including ones whose condition is still false. With two threads it rarely matters, but with three threads printing in turn, notifyAll after printing 1 wakes both other threads, and only one of them should print 2. Each must recheck the condition after it gets the lock back, and the one that is not due goes back to waiting. The while loop is the standard idiom: wait while the condition is false, act once it is true, all under the same lock.
4Alternatives: Semaphores and Conditions
A Semaphore holds permits; acquire() takes one, waiting if none is available, and release() returns one. Two semaphores make the turn-taking explicit: the odd thread may run when it holds a permit from oddTurn, and it gives the turn away by releasing evenTurn.
This version has no shared counter and no wakeup loop to get wrong, because a permit cannot be claimed spuriously. In real code I would use acquire() and handle InterruptedException; acquireUninterruptibly keeps the example short. A ReentrantLock with two Conditions, oddTurn and evenTurn, is the third option: it works like the monitor version, still with while loops around await(), but lets each thread signal exactly the thread whose turn it is instead of waking everyone.
5Clean Shutdown and Interrupts
The main thread calls join() on both workers so the program does not report completion while they are still printing. join() can throw InterruptedException, which the main method declares here.
Inside the worker, catching InterruptedException and doing nothing would erase the signal that someone wants the thread to stop. Calling Thread.currentThread().interrupt() sets the flag again, so code further up, or a thread pool, can still see it, and then we return. That is the standard way to handle an interrupt we cannot pass on, since Runnable.run cannot throw checked exceptions.
6Follow-up questions
How would you extend this to three threads printing in turn?
I give each thread an id of 0, 1 or 2 and change the condition to next % 3 != (id + 1) % 3, or simply keep a turn variable from 0 to 2. Each thread waits in a while loop until it is its turn, prints, increments, and calls notifyAll. notifyAll matters now: with notify, the JVM might wake the one thread whose turn it is not, which goes back to waiting, and the right thread never wakes, so the program hangs. With ReentrantLock I would use one Condition per thread and signal exactly the next one.
Why not use Thread.sleep to alternate?
Because sleeping does not coordinate anything; it only makes a particular interleaving likely. Under load, garbage collection or a slow machine, the timing changes and the output goes out of order. Correct turn-taking needs shared state checked under a lock, or a primitive such as a semaphore.
Would notify() be enough with two threads?
Here, yes, because there is only one other waiting thread and it is always the one whose turn it is. I still use notifyAll because it stays correct if a third thread is added or if another part of the code waits on the same lock, and the cost for two threads is negligible.
7Conclusion
In this answer, we made two threads take turns with one lock and a shared counter: each thread waits inside synchronized while next does not have its parity, then prints, increments and calls notifyAll. The wait sits in a while loop because of spurious wakeups and because notifyAll wakes threads whose condition may still be false, and the extra next <= 10 check lets the last waiting thread exit. Two semaphores handing a permit back and forth, or a ReentrantLock with one Condition per thread, are cleaner alternatives, and the main thread joins both workers while workers restore the interrupt flag.
Open with
I would use one lock object and a shared counter called next, starting at 1, which is only read and written inside synchronized on that lock. Each thread knows its parity, one for odd and zero for even.
Then, if they want more
In a loop while next is at most 10, the thread checks, inside the lock, whether next has its parity. If not, it calls lock.wait, which releases the lock and sleeps. When it is its turn, it prints next, increments it, and calls notifyAll so the other thread wakes and rechecks.
I also check next against 10 after waking, because after the even thread prints 10, the odd thread is still waiting and has to see that the job is done and leave, otherwise it waits forever. The wait has to be in a while loop for two reasons.
Java allows spurious wakeups, so wait can return without any notify, and notifyAll wakes every waiting thread, even ones whose condition is still false. So waking up never proves it is my turn, I always recheck before acting. In main I start both threads and join them.
If a worker is interrupted while waiting, I restore the flag with Thread.currentThread().interrupt and return, rather than swallowing it. As alternatives, two semaphores work nicely, one starting with a permit for the odd thread, each thread acquiring its own and releasing the other's, and a ReentrantLock with a Condition per thread lets me signal exactly the next thread.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write Java code with two threads where one prints odd numbers and the other prints even...": https://scrivio-interview-library.netlify.app/java/coding-problems/80a9cfc4aa/