Java Concurrency Program · OT63
Print Numbers in Sequence Using Three Threads in Java
Thread i may print number n only when (n - 1) % 3 == i. Every thread waits for its turn, prints and signals the others.
Problem Statement
Start three threads T1, T2 and T3 that print the numbers 1 to 9 in order, in strict rotation: T1 prints 1, T2 prints 2, T3 prints 3, T1 prints 4, and so on.
The rotation must hold no matter which thread the scheduler runs first.
Input/Output Examples
1 to 3OutputT1: 1, T2: 2, T3: 3Explanation: one number per thread.7 to 9OutputT1: 7, T2: 8, T3: 9Explanation: the rotation repeats.threads started T3, T2, T1Outputstill starts with T1: 1Explanation: turns are enforced, not assumed.Visual Explanation
- next = 1may printT1(1 - 1) % 3 = 0
- next = 2may printT2(2 - 1) % 3 = 1
- next = 3may printT3(3 - 1) % 3 = 2
- next = 4may printT1back to T1
- Done1 … 9 in rotation
(next - 1) % 3. The other two wait on the condition.signalAll() wakes all waiting threads after each print; the two that are not next simply check the counter and wait again.
Approaches
Both approaches enforce the same rotation. One uses a lock and a shared condition; the other passes a permit around a ring of semaphores.
Approach 1: ReentrantLock and Condition (Recommended)
Idea: each thread waits on a Condition until (next - 1) % 3 equals its id, prints, then signals all.
- Lock, and await while it is not this thread's turn.
- Stop when the counter passes 9, signalling the others so they stop too.
- Print, increment,
signalAll()and unlock infinally.
Time: O(n) · Space: O(1).
Approach 2: Ring of Semaphores
Idea: thread i acquires semaphore i, prints, then releases semaphore (i + 1) % 3.
- Semaphore 0 starts with one permit; the others start with none.
- Each thread acquires its own semaphore before printing.
- After printing, it releases the next 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: ReentrantLock and Condition (Recommended)
Unlocking in finally guarantees the lock is released even if the thread is interrupted.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ThreeThreadsLock {
private static final ReentrantLock lock = new ReentrantLock();
private static final Condition turnChanged = lock.newCondition();
private static int next = 1;
private static final int MAX = 9;
private static final List<String> log = Collections.synchronizedList(new ArrayList<>());
// Thread id (0, 1, 2) may print number n only when (n - 1) % 3 == id
static void run(int id) {
while (true) {
lock.lock();
try {
while (next <= MAX && (next - 1) % 3 != id) {
turnChanged.await();
}
if (next > MAX) {
turnChanged.signalAll();
return;
}
log.add("T" + (id + 1) + ": " + next++);
turnChanged.signalAll();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[3];
for (int i = 2; i >= 0; i--) { // start in reverse to show the order is enforced
final int id = i;
threads[i] = new Thread(() -> run(id));
threads[i].start();
}
for (Thread t : threads) {
t.join();
}
log.forEach(System.out::println);
}
}
T1: 1 T2: 2 T3: 3 T1: 4 T2: 5 T3: 6 T1: 7 T2: 8 T3: 9
Time complexity: O(n) · Space complexity: O(1).
Approach 2: Ring of Semaphores
Only the next thread is ever woken, so there are no wasted wake-ups.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Semaphore;
public class ThreeThreadsSemaphore {
private static final int MAX = 9;
private static final Semaphore[] turn = {new Semaphore(1), new Semaphore(0), new Semaphore(0)};
private static final List<String> log = Collections.synchronizedList(new ArrayList<>());
// Thread i waits on its own semaphore, prints, then releases the next thread's semaphore
static void run(int id) {
for (int n = id + 1; n <= MAX; n += 3) {
try {
turn[id].acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
log.add("T" + (id + 1) + ": " + n);
turn[(id + 1) % 3].release();
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[3];
for (int i = 2; i >= 0; i--) {
final int id = i;
threads[i] = new Thread(() -> run(id));
threads[i].start();
}
for (Thread t : threads) {
t.join();
}
log.forEach(System.out::println);
}
}
T1: 1 T2: 2 T3: 3 T1: 4 T2: 5 T3: 6 T1: 7 T2: 8 T3: 9
Time complexity: O(n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| ReentrantLock and Condition | O(n) | O(1) |
| Ring of Semaphores | O(n) | O(1) |
Here n is the highest number. Each number is printed once; with signalAll(), each step briefly wakes the two threads that are not next.
Interview Tips and Recommended Approach
- Generalise the rule. For
kthreads, threadiprints when(n - 1) % k == i. - Unlock in
finally. Forgetting it can block every thread forever. - Compare the tools. Semaphores wake exactly one thread; a shared condition is simpler to generalise.
- Join the threads before the program exits or reads shared results.
Recommended Approach: ReentrantLock and Condition
Why: it scales to any number of threads by changing one modulus, and it shows how Condition replaces wait()/notify() with explicit locks.