Forums Register Login

about Threads notify!

+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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 ]
This is my favorite show. And this is my favorite tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 523 times.
Similar Threads
Question On Object Locks.
wait and notify..test
Using wait/notify()
Problem On using wait() in THreads
Confusing in wait notify
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 13:26:59.