Java Threads Print Alternative Odd Even Numbers
What we are trying to achieve
- Print Class (Print.java) with two synchronized methods even() and odd() which print even or odd numbers respectively.
- Each method is synchronized so that two threads cannot execute them concurrently.
- Each method first calls notifyAll() to so that other threads that are waiting can be wake up.
- It then prints a number (even or odd) and then calls the wait() method on the current thread so it goes to waiting state.
Java Code
class Print {
int max;
public Print(int max) {
this.max = max;
}
public synchronized void even() throws InterruptedException {
for (int i = 0; i <= max; i++) {
notifyAll();
if (i % 2 == 0)
System.out.println(Thread.currentThread().getName() + ":: " + i);
wait();
}
}
public synchronized void odd() throws InterruptedException {
for (int i = 0; i <= max; i++) {
notifyAll();
if (i % 2 != 0)
System.out.println(Thread.currentThread().getName() + ":: " + i);
wait();
}
}
}
Print print = new Print(10);
//Thread to print even numbers
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
print.even();
} catch (InterruptedException e) {
}
}
});
//Thread to print odd numbers
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
print.odd();
} catch (InterruptedException e) {
}
}
});
t1.setName("Even Thread");
t2.setName(" Odd Thread");
t1.start();
t2.start();
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
- From the odd() or even () method we have to first call notify or notifyAll() first.
- Both odd() or even() method should be synchronized otherwise calling notifyAll() or wait() will throw exception