I have two threads running t1 and t2. When t2 notifies t1, immediately t2 should go to wait state. However, this is not possible as once it notifies t1, it should finish its current process and only after the end of the current thread execution, the t1 execution starts. But i would like to start t1 immediately after t2 notifies so that i can put t2 in wait state for t1 to notify inside the while loop. Is this possible with synchronized block?. I have tried the following code that does not work. I have also commented the coding lines to mention the way i would like to code.
public void passNo(int data)//thread t1
{
this.data1=data;
synchronized(thread2)
{
System.out.println("thread1 running");
data1=data1+100;
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread1 going to notify thread two");
thread2.notify();
/* try {
thread1.wait();
} catch (Exception e) {
e.printStackTrace();
}*/
}//sync
try {
Thread.sleep(1000);
} catch (Exception e) {}
System.out.println("im done, receiver go");
//}
}
public void ramos(int data)//thread t2
{
synchronized(thread1)
{
try{
System.out.println("I am thread 2 waiting for thread 1");
thread1.wait();//Problem-not notified ever by sender
System.out.println("Notified by sender thread");}
catch(InterruptedException ex){}
System.out.println("I am released");
n=obj.getInteger();
setInteger();
System.out.println("Notified");
}//sync
j++;
//}//while
}
class ClaObj
{
public static void main(String[] args)
{
Sender s=new Sender();
Receiver r=new Receiver();
r.classobj(s);
Thread thread1 = new Thread(s);
Thread thread2 = new Thread(r);
s.sendthrobj(thread1);
r.recvthobj(thread1);
thread1.start();
thread2.start();
}
}