This week's book giveaway is in the Design and Architecture forum.
We're giving away four copies of Communication Patterns: A Guide for Developers and Architects and have Jacqui Read on-line!
See this thread for details.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Am I right about wait() and notifyAll()

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Ranchers!
I need som guidens about wait() and notifyAll().
If I have a program that has 2 threads and I call start on both threads then the first started Thread enters run(). In run I will do my code , call methods and so on. If I like to call a syncronized method and wait() then only one thread shall execute this method. The other thread must run another method that calls notifyAll()! Is this right? I've seen example code that has wait in both syncronized methods and calls notifyAll() in both syncronized methods. Can someone please make an example how to correctly use wait() notifyAll() in an short program. Please be kind to comment the code.
Thanks
// Mathias
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Mathias
If you have two threads that are both running and both try to call methods that are synchronized on the same object then only one can enter the method. The other thread would have to keep trying to access the method until it gained access.
Think of it like a doctors office and a waiting room. Only one person can be in any one doctors office at a time, but any number can be in the waiting room. If a person (thread) is already in the office (synchronized code) then no others can get in.
Assume a thread/person is in the office/synchronized code but for some reason can not continue, that thread calls wait() and goes and sits in the waiting room. Now the office is open and another thread can enter. If another thread had never entered the office but was constantly trying to get in (say it was waiting outside the door) it can now do so. After some time in the office the new thread can no longer continue either so it will also call wait and go to the waiting room. Just before it calls wait it will call notifyAll() (sort of like letting everyone in the waiting room know the office is open) and all of the threads in the waiting room will try to get in the office/synchronized code. the one that called notifyAll() will now wait until it is notified.
A couple of points to remember; wait(), notify(), and notifyAll() can only be called from within synchronized code (you cant go to the waiting room until you've been in the office and you cant let anyone else know the office is open unless you've been in it). When a thread calls notify, notifyAll it only effects those other threads waiting on the same objects monitor. (you cant let other people know that some other doctors office is open if you're in a different one).
Here is a code example:
This example is a bit contrived but it will show you what is going on. The main method creates two thread objects and passes the same SharedObject to each them. The sharedObject has two synchronized methods that it uses to just count up and count down. When the MyOtherThread object gets to the countup mthod it starts to wait because the ready flag is set to true.
When it initially enters the countup method it gets the lock on the SharedObject object, but when it calls wait it releases the lock. So that when the MyThread object gets to the countdown method it gets the lock on it. Because the flag is true the method executes.
After the for loop it changes the flag and then calls notifyAll(). notifyAll() will wakeup all of the threads that are waiting on that object and they will all begin to seek the lock on it.

hope that helps you, if not, let me know

Dave
SCJP
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I also had the same problem yesterday and I wrote an example program to understand this . Hope this helps you.
Suppose we have two threads .First thread is started and is in run(). It calls the second thread and it is in run now. If u want
thread1 to wait() until thread2 sends notify() , this is what u could do.
Program 1: Thread1.java
class Thread1 extends Thread {


/** Overwrite the method from java.lang.Thread */
public void run() {
System.out.println("Thread1.run()");
try{
for(;;) {

String status = "P";
// pass "this" object to thread 2.
new Thread2(status,this).start();
// thread1 now waits until it gets notify from thread2
waitmethod();

}

}

catch (Exception e){
System.out.println("Caught exception in Thread1" + e.toString());
}
}
public void waitmethod(){
try{

synchronized(this) {
System.out.println("Waiting");
wait();
}
}

catch (Exception e){
System.out.println("Caught exception in waitmethod" + e.toString());
}
}
public void notifymethod() {

try{
synchronized(this) {
System.out.println("Notifying");
notifyAll();
}
}

catch (Exception e){
System.out.println("Caught exception in notifymethod" + e.toString());
}
}

}
Program2: Thread2.java
class Thread2 extends Thread {

private String _status;
private Thread2 _ch;

public void run() {

System.out.println("Iam in Thread2.run() ");
_status = "C";
System.out.println(_status);
// once thread2 is done , it gets synchronized lock on // thread1 and calls thread1's notifymethod
synchronized(_ch) {
_ch.notifymethod();
}
// now u are back to Thread1 to iterate next time.

}




public Thread2(String status,Thread1 ch) {

_status = status;
_ch = ch;
}
}
Hope this makes u understand wait() and notifyall() methods.
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dave and Poornima, those were 2 very good examples of wait() and notify(). thanks for sharing them with us.
Poornima, I do have a quick question about your code though. I haven't compiled it myself but seems like the statement _ch = ch has datatype Thread2 on LHS and Thread1 on RHS. Is that a typo or am I missing something? I believe _ch should be declared as Thread1.
thanks,
GP
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks both I'm going though them as we "speak". I will carefully try to understand exactly was going on. I'll be back to post on this topic if I still not getting it.
 
Poornima Ganesh
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ooops...It was a typo error Girish as u mentioned. It has to be private Thread1 _ch; in the Thread2.java program.I had different names of the programs that I compiled. So I couldnt cut and paste the same one . Thanks for pointing out .
 
Did you just should on me? You should read this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic