Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about Threads notify!

 
Paul J
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everbody,
I am reading a book about Thread.It tell me :
"The method wait() and notify() are instance methods of Object.In the same way that every objet has a lock,every object can have a list of threads that are waiting for a signal from the object.A thread gets on this list by executing the wait() method of the target object.From that moment,it doesn't execute any further instructions until the notify()method of the target object is called."
I write a example:
------------------------------
public class test
{
public static void main(String [] args)
{
ThreadB b=new ThreadB();
b.start();
synchronized(b){
try{
System.out.println("Waiting for b to complete");
b.wait();
}catch(InterruptedException e){
System.out.println("InterruptedException open");
}
}
System.out.println("Total is :"+b.total);
}
};
class ThreadB extends Thread
{
int total;
public void run(){
synchronized(this){
for(int i=0;i<100;i++){
total+=i;
}
notify();
}
}
};
-----------------------
It can be compiled and run correctly without question.But in fact,if I delete the "notify()" in method run() of class ThreadB,it can still be compiled and run correctly.Why?
[ March 18, 2002: Message edited by: Paul J ]
 
R K Singh
Ranch Hand
Posts: 5384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think compiler does not force you to call notify().
As notify() can be called on same object from anywhere.
================ FILE Test020318.java =======

=================== FILE Test020318Part_2.java ===

As you can see there are TWO different file but notify() can be called on the object of ThreadB.
So compiler does not force you to put notify() in same file or in same class.
HTH
CMIW
 
Paul J
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks your response.I think you are right.But I write some test code as follows,It can run correctly without "notify()" in any Class.

We can see,there is not notify in ThreadB.It can still run ,which isn't in accord with the ideal--"Must notify() when use wait(). ".
Execute my english.
[ March 18, 2002: Message edited by: Paul J ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic