Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using wait() and notify()

 
Siddhartha Bhattacharya
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I want to notify a waiting thread from another thread how do i do this?
ex
class Thread1 extends Thread
{
public synchronized void method()
{

try{ wait(10000);}
catch(){}
}
class Thread2 extends Thread
{
public void notifyThread1()
{

}

}
How do i notify Thread1 from Thread2?
 
David Hadiprijanto
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Siddhartha,
If thread A is waiting, using object B, and you want thread C to notify A, then you will need a reference to object B in thread C, and invoke B.notify();
In your sample code, since you are synchronizing the whole method, the wait is synchronized on the corresponding object/instance (of Thread1).
So, you need to have a reference to the instance of Thread1 in Thread2.notifyThread1(), and invoke the .notify(); method on that instance.
Hope this helps.
 
Siddhartha Bhattacharya
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried that.
Thread1 th;
In Thread2 notifyThread1() method in sync block doing th.notify() gives an exception saying that the current thread is not the owner.
 
David Hadiprijanto
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to synchronize on the object you were invoking notify() on.
Otherwise you get an exception.
See sample code below, Thread2 notifyThread1() has synchronized block using the th object, on which it invoke the notify() method.
This sample code compiles and runs fine.
The output, as expected :
Thread1 Waiting...
Thread2 Notifying Thread1...
Thread1 Notified...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic