• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Struggling to get wait()/notify() to work

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For some reason this code freezes at the output of:

1
1

Been really struggling to get wait/notify to work. Can someone please tell where I can get some good examples. I have the K & B book, but are there any other good examples?


public class RunningMan implements Runnable{


public RunningMan() {
}

public synchronized void run() {
for (int x = 1; x < 77; x++){
notify();
System.out.println(x);
try {
wait();
}catch (Exception e){

};
}
}

public static void main(String[] args) {
Thread t1 = new Thread(new RunningMan());
Thread t2 = new Thread(new RunningMan());
t1.start();
t2.start();
}

}
 
Ranch Hand
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you call wait, or notify, the JVM will wait/notify the object the method is called on. In your code, each thread is calling wait/notify on a different object. Try using the same object by perhaps passing the same object into the constructor of each Runnable. And then you need to synchronize on the object you call wait on, so you can remove the synchronized from the run method.

something like


There are other problems in the code, but that should help to explain your first one.
 
Doody calls. I would really rather that it didn't. Comfort me wise and sterile tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic