This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Using wait() and notify() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Using wait() and notify()" Watch "Using wait() and notify()" New topic
Author

Using wait() and notify()

Siddhartha Bhattacharya
Ranch Hand

Joined: Jul 02, 2002
Posts: 36
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

Joined: Sep 14, 2003
Posts: 52
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

Joined: Jul 02, 2002
Posts: 36
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

Joined: Sep 14, 2003
Posts: 52
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...
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Using wait() and notify()