Tech Interview RoomStudy guides

Concurrency

Print numbers 1 to N alternately from two threads (odd and even).

Intermediate · 2 min read · Lesson 2 of 5 in Concurrency

Problem

Thread T1 prints odd numbers and T2 prints even numbers, producing 1, 2, 3, ..., N in order. A classic test of thread coordination.

Approach

Share a counter and a monitor. Each thread waits while it is not its turn (counter % 2 tells whose turn), prints, increments and notifies the other. Waiting in a while loop is essential. An alternative is two Semaphores passing a permit back and forth, which reads very clearly.

java
import java.util.concurrent.Semaphore;

class OddEvenPrinter {
    private final int max;
    private int counter = 1;

    OddEvenPrinter(int max) { this.max = max; }

    void print(boolean odd) {
        synchronized (this) {
            while (true) {
                while (counter <= max && (counter % 2 == 1) != odd) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
                if (counter > max) {
                    notifyAll();     // let the other thread exit too
                    return;
                }
                System.out.println(Thread.currentThread().getName() + ": " + counter++);
                notifyAll();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        OddEvenPrinter p = new OddEvenPrinter(10);
        Thread odd = new Thread(() -> p.print(true), "odd");
        Thread even = new Thread(() -> p.print(false), "even");
        odd.start();
        even.start();
        odd.join();
        even.join();
        SemaphoreVersion.run(10);
    }
}

class SemaphoreVersion {
    static void run(int max) throws InterruptedException {
        Semaphore oddTurn = new Semaphore(1), evenTurn = new Semaphore(0);
        Thread odd = new Thread(() -> loop(1, max, oddTurn, evenTurn));
        Thread even = new Thread(() -> loop(2, max, evenTurn, oddTurn));
        odd.start();
        even.start();
        odd.join();
        even.join();
    }

    private static void loop(int start, int max, Semaphore mine, Semaphore other) {
        for (int i = start; i <= max; i += 2) {
            try {
                mine.acquire();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
            System.out.println(i);
            other.release();
        }
    }
}

Complexity

O(N) prints; each step costs a context switch, which is the point of the exercise rather than performance.

Follow-up questions interviewers ask

Try answering each one before you open it.

How would you generalise it to three threads printing 1, 2, 3, 1, 2, 3...?

Give each thread an index k (0, 1, 2) and wait while counter % 3 != k, then print and notifyAll(). With semaphores, create an array of three semaphores where only the first starts with a permit, and each thread releases the next one: sems[(k + 1) % 3].release().