Java Concurrency Interview

Live coding puzzles question 171 of 180 mid

Print numbers 1 to 100 with two threads, one printing odd and one even, in order.

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.

puzzle wait-notify

Quiz yourself on Live coding puzzles Suggest a correction