Java Wait and Notify Threads Program
class Que1 {
int n;
boolean flag = false;
synchronized int get() {
if(!flag)
try{
wait();
}catch (InterruptedException e) {
System.out.println(“Exception”);
}
System.out.println(“Get: ” +n);
flag = false;
notify();
return n;
}
synchronized void put(int n) {
if(flag)
try{
wait();
}catch (InterruptedException e) {
System.out.println(“Exception”);
}
this.n = n;
System.out.println(“Put: ” +n);
flag = true;
notify();
}
}
class Producer1 implements Runnable{
Que1 q;
Producer1(Que1 q){
this.q = q;
new Thread(this,””).start();
}
public void run() {
int i=0;
while(i<=10){
q.put(i++);
}
}
}
class Consumer1 implements Runnable{
Que1 q;
Consumer1(Que1 q){
this.q = q;
new Thread(this,””).start();
}
public void run() {
while(true){
q.get();
}
}
}
public class WaitNotifyDemo {
public static void main(String args[]) {
Que1 q = new Que1();
new Producer1(q);
new Consumer1(q);
}
}
Result:
Put: 0
Get: 0
Put: 1
Get: 1
Put: 2
Get: 2
Put: 3
Get: 3
Put: 4
Get: 4
Put: 5
Get: 5
Put: 6
Get: 6
Put: 7
Get: 7
Put: 8
Get: 8
Put: 9
Get: 9
Put: 10
Get: 10
Nice post , just to add while using wait() and notify() method in Java Its important to understand that wait() should be called in a loop if multiple thread can wait on same condition because when threads gets notified there is no guarantee which thread will get lock and return from wait method. so if suppose two threads A and B are waiting on a condition and receives notification then both try to get lock , luckily A got lock and executed and made the condition false again but if thread B doesn’t check the condition again after getting lock (which is why we need to check condition in loop) it will run even if it supposed to wait. So its important to recheck the condition after getting lock and wait again if condition is false again.