Print 1 to 100 using 3 Threads
- Thread-1 prints: 1, 4, 7, 10, …
- Thread-2 prints: 2, 5, 8, 11, …
- Thread-3 prints: 3, 6, 9, 12, …
Output becomes:
T1 -> 1
T2 -> 2
T3 -> 3
T1 -> 4
T2 -> 5
T3 -> 6
...
T1 -> 100
One way is using wait() / notifyAll() and a shared counter.
package exercise.threads;
public class Print1To100 {
private int number = 1;
private final int MAX = 100;
private int nextTurn = 1;
private synchronized void print(int threadId){
while (number <= MAX) {
while (nextTurn != threadId && number <= MAX){
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
if(number > MAX)
{
notifyAll();
return;
}
System.out.println(Thread.currentThread().getName() + "--> " + number);
number++;
nextTurn = (nextTurn % 3) + 1;
notifyAll();
}
}
public static void main(String[] args) {
Print1To100 printer = new Print1To100();
Thread t1 = new Thread(() -> printer.print(1),"Thread-1");
Thread t2 = new Thread(() -> printer.print(2),"Thread-2");
Thread t3 = new Thread(() -> printer.print(3),"Thread-3");
t1.start();
t2.start();
t3.start();
}
}