Live coding puzzles question 171 of 180 mid
Print numbers 1 to 100 with two threads, one printing odd and one even, in order.
- Two threads with
Thread.sleep(1)between prints - Correct: One shared monitor, a counter, and each thread waiting in a
whileloop until the parity matches - Two
AtomicIntegers - A
CountDownLatchper number
The shape they want, with the while loop and the notifyAll in the right places:
class OddEven {
private final Object lock = new Object();
private int n = 1;
void print(boolean odd, int limit) throws InterruptedException {
while (true) {
synchronized (lock) {
while (n <= limit && (n % 2 == 1) != odd) {
lock.wait();
}
if (n > limit) {
lock.notifyAll(); // release the other thread before leaving
return;
}
System.out.println(Thread.currentThread().getName() + ": " + n++);
lock.notifyAll();
}
}
}
}
Two details separate a pass from a fail: the while rather than if around wait, and the final
notifyAll before returning, without which the other thread waits forever at the end.
A Semaphore pair is an equally good answer and often shorter: each thread releases the other's
permit after printing.