🔥 Launch Offer: Interview Preparation Bundle @ ₹2,499 ₹9,999 • 75% OFF. Offer expires in 🔥 Launch Offer: Interview Preparation Bundle @ ₹2,499 ₹9,999 • 75% OFF. Offer expires in Interview Preparation Bundle @ ₹2,499 ₹9,999

00:00:00 Get Bundle
home / practice / print-odd-even-with-two-threads
medium Multithreading

Print odd & even with two threads

Start two threads. One prints odd numbers, the other even numbers, from 1 to N, in ascending order with no races and no missing values. Use wait / notify (or an equivalent lock).

Example

N = 5
Output: 1 2 3 4 5

Starter code

public class OddEvenPrinter {
    private final int n;
    private int current = 1;
    private final Object lock = new Object();

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

    public void printOdd() {
        // TODO
    }

    public void printEven() {
        // TODO
    }

    public static void main(String[] args) {
        OddEvenPrinter p = new OddEvenPrinter(5);
        Thread t1 = new Thread(p::printOdd, "odd");
        Thread t2 = new Thread(p::printEven, "even");
        t1.start();
        t2.start();
    }
}

Solution

public class OddEvenPrinter {
    private final int n;
    private int current = 1;
    private final Object lock = new Object();

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

    public void printOdd() {
        synchronized (lock) {
            while (current <= n) {
                while (current % 2 == 0) {
                    try { lock.wait(); } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
                if (current > n) break;
                System.out.print(current + " ");
                current++;
                lock.notifyAll();
            }
        }
    }

    public void printEven() {
        synchronized (lock) {
            while (current <= n) {
                while (current % 2 == 1) {
                    try { lock.wait(); } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
                if (current > n) break;
                System.out.print(current + " ");
                current++;
                lock.notifyAll();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        OddEvenPrinter p = new OddEvenPrinter(5);
        Thread t1 = new Thread(p::printOdd, "odd");
        Thread t2 = new Thread(p::printEven, "even");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}