• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Jared Folino
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • 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();
}

}
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!