Java Concurrency Program · OT62
Print Odd and Even Numbers Using Two Threads in Java
Two threads share a counter. Each one waits until the counter is its kind of number, prints it, increments it and wakes the other thread.
Problem Statement
Start two threads: one prints the odd numbers and the other the even numbers from 1 to 10, so that the combined output is 1, 2, 3, …, 10 in order.
The order must not depend on which thread starts first or on timing.
Input/Output Examples
two threadsOutputodd 1, even 2, odd 3, …, even 10Explanation: strict alternation.even thread started firstOutputstill begins with 1Explanation: it waits for its turn.after 10Outputboth threads exitExplanation: neither waits forever.Visual Explanation
- next = 1turnoddeven thread waits
- print 1turnevennext = 2, notifyAll()
- print 2turnoddnext = 3, notifyAll()
- …repeat until next > 10
- Done1 2 3 … 10
notifyAll() wakes the other thread to check again.Waiting inside a while loop, not an if, protects against spurious wake-ups and against being woken when it is still not your turn.
Approaches
Both approaches enforce strict turns. One uses a lock with wait()/notifyAll(); the other passes permits between two semaphores.
Approach 1: wait() and notifyAll() (Recommended)
Idea: both threads synchronise on one lock; each waits while the counter has the wrong parity, then prints and notifies.
- Inside
synchronized (lock), wait while it is not this thread's turn. - Stop when the counter passes 10, waking the other thread so it can stop too.
- Print, increment the counter and call
notifyAll().
Time: O(n) · Space: O(1).
Approach 2: Two Semaphores
Idea: the odd thread starts with one permit; each thread acquires its own semaphore, prints, then releases the other's.
oddTurnstarts with 1 permit,evenTurnwith 0.- Each thread acquires its own semaphore before printing.
- After printing, it releases the other thread's semaphore.
Time: O(n) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. The threads are coordinated so strictly that the output is identical on every run (checked over 25 runs); both programs print the same lines.
Approach 1: wait() and notifyAll() (Recommended)
The classic answer, and the one that tests understanding of monitors.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class OddEvenWaitNotify {
private static final Object lock = new Object();
private static int next = 1;
private static final int MAX = 10;
private static final List<String> log = Collections.synchronizedList(new ArrayList<>());
// Each thread waits until it is its turn (next is odd or even), prints, then wakes the other
static void run(boolean odd) {
while (true) {
synchronized (lock) {
while (next <= MAX && (next % 2 == 1) != odd) {
try {
lock.wait(); // always wait in a loop
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
if (next > MAX) {
lock.notifyAll();
return;
}
log.add((odd ? "odd " : "even") + " thread: " + next);
next++;
lock.notifyAll();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread oddThread = new Thread(() -> run(true));
Thread evenThread = new Thread(() -> run(false));
evenThread.start(); // starting order does not matter
oddThread.start();
oddThread.join();
evenThread.join();
log.forEach(System.out::println);
}
}
odd thread: 1 even thread: 2 odd thread: 3 even thread: 4 odd thread: 5 even thread: 6 odd thread: 7 even thread: 8 odd thread: 9 even thread: 10
Time complexity: O(n) · Space complexity: O(1).
Approach 2: Two Semaphores
The hand-over is explicit, so there is no shared counter to check.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Semaphore;
public class OddEvenSemaphore {
private static final Semaphore oddTurn = new Semaphore(1); // odd goes first
private static final Semaphore evenTurn = new Semaphore(0);
private static final int MAX = 10;
private static final List<String> log = Collections.synchronizedList(new ArrayList<>());
// Each thread acquires its own permit, prints, then releases the other thread's permit
static void run(boolean odd) {
Semaphore mine = odd ? oddTurn : evenTurn;
Semaphore other = odd ? evenTurn : oddTurn;
for (int n = odd ? 1 : 2; n <= MAX; n += 2) {
try {
mine.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
log.add((odd ? "odd " : "even") + " thread: " + n);
other.release();
}
}
public static void main(String[] args) throws InterruptedException {
Thread oddThread = new Thread(() -> run(true));
Thread evenThread = new Thread(() -> run(false));
evenThread.start();
oddThread.start();
oddThread.join();
evenThread.join();
log.forEach(System.out::println);
}
}
odd thread: 1 even thread: 2 odd thread: 3 even thread: 4 odd thread: 5 even thread: 6 odd thread: 7 even thread: 8 odd thread: 9 even thread: 10
Time complexity: O(n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| wait() and notifyAll() | O(n) | O(1) |
| Two Semaphores | O(n) | O(1) |
Here n is the highest number printed. Each number is printed once; the threads spend the rest of the time blocked, not spinning.
Interview Tips and Recommended Approach
- Always wait in a loop.
if (notMyTurn) wait();breaks on spurious wake-ups. - Use
notifyAll()unless you are sure only the right thread can be waiting. - Plan termination. The last thread to finish must wake the other one, or it waits forever.
- Know the modern tools. Semaphores or
ReentrantLockconditions make the hand-over more explicit.
Recommended Approach: wait() and notifyAll()
Why: it shows the fundamentals of thread communication, monitors, waiting and notification, which is what this interview question tests.