I am trying to use wait() and notify() on a class to notify the waiting thread but the scenario is whoever go first into the synchronized block will wait for other to print some values and notify the waiting thread. but the waiting thread is keep waiting. what am doing wrong.
public class MyRunnableClass implements Runnable {
public static boolean transfer = false;
public static boolean isAnyThreadWaiting = false;
int a=10;
@Override
public void run() {
// TODO Auto-generated method stub
synchronized(this) {
System.out.println("I am Thread : "+Thread.currentThread().getName()+" and I first occuipied block");
try {
if(isAnyThreadWaiting)
MyRunnableClass.transfer=true;
if(!MyRunnableClass.transfer&&!isAnyThreadWaiting) {
System.out.println("I am Thread : "+Thread.currentThread().getName()+" and I am going to wait");
while(!MyRunnableClass.transfer) {
isAnyThreadWaiting=true;
this.wait();
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0; i<a;i++) {
System.out.println("I am Thread : "+Thread.currentThread().getName()+" Value of a is : "+i );
}
a=0;
isAnyThreadWaiting=false;
this.notify();
}
}
public static void main(String [] args) throws InterruptedException {
MyRunnableClass runnable1= new MyRunnableClass();
Thread thread1=new Thread(runnable1,"t1");
Thread thread2=new Thread(runnable1,"t2");
thread1. start();
thread2. start();
}
}