Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronized and wait()  RSS feed

 
David Thomas
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Trying to get to grips with Threads using SCJP by Sierra Bates and copied the example to demonstrate Thread Interaction see below for code. Now I thought the wait() meant that ThreadA will not complete until ThreadB excutes the notify(). However I find if I comment out the notify() the wait is ignored?

Is that correct or should the program hang until the notify() is executed?

Thanks

ps. sorry should have posted this in the "Beginging Java"

package thread;

public class ThreadA {

public static void main(String[] args) {
ThreadB b = new ThreadB();
b.setName("B Thread");
b.start();

synchronized(b){
try{
System.out.println("waiting for " + b.getName());
b.wait(); // must have lock.. then it can be release temporily while waiting for notify
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Total is "+ b.total);
}

}

}
class ThreadB extends Thread {
int total;

public void run(){
synchronized(this){
System.out.println(Thread.currentThread().getName());
for (int i=0;i<100;i++){
total += i;
}
// comment out notify();
}
}
}
 
Andrei Matyas
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

This is normal because ther is no other that that may do a notify. In this case the jvm is smart and the wait call has no effect.

Try adding another thread :


 
David Thomas
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks,will try that.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!