aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread wait() and notify() Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Thread wait() and notify()" Watch "Thread wait() and notify()" New topic
Author

Thread wait() and notify()

Ayusarap Muhi
Greenhorn

Joined: Mar 26, 2008
Posts: 1
Hello everyone,

I would just like to ask if the following code example in the Sierra Bates SCJP Reviewer below is correct. Is it possible for b.wait() in line 9 to wait forever if the notify() action in line 24 comes first?


1. class ThreadA {
2. public static void main(String [] args) {
3. ThreadB b = new ThreadB();
4. b.start();
5.
6. synchronized(b) {
7. try {
8. System.out.println("Waiting for b to complete...");
9. b.wait();
10. } catch (InterruptedException e) {}
11. System.out.println("Total is: " + b.total);
12. }
13. }
14. }
15.
16. class ThreadB extends Thread {
17. int total;
18.
19. public void run( ) {
20. synchronized(this) {
21. for(int i=0;i<100;i++) {
22. total += i;
23. }
24. notify( );
25. }
26. }
27. }


Thanks in advance.

Ashok Kumar Babu
Ranch Hand

Joined: Jul 25, 2006
Posts: 129
Yes.

After line no:9, the main thread will wait(In Runnable state) until line no:24 executes or until the run method completes.

The Logic would be Main thread is waiting for threadB to complete the total and in Main thread you are displaying it.


Ashok<br /> <br />SCJP 91%<br />SCWCD 88%
yu yong
Ranch Hand

Joined: Mar 09, 2008
Posts: 44
To Ayusarap:
I dont think so. In my mind, your code`s result is dynamic. Bug I am not sure about it. Can anyone explain it in detail. Thanks a lot.


Yours sincerely,<br />yuyong<br /> <br /> <br /> E-mail:yuyong22@hotmail.com<br /> msn: yuyong22@hotmail.com<br /> Skype:yuyong88
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

try this in between line 4 and 6 of your code :


Most probably(99.99999%) this will clarify Kathy and Bert..!!


Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Thread wait() and notify()
 
Similar Threads
wait() will wait forever
See this thread interaction code
Multithreading: How can total be nearly 5,000 even though loop is up to 100?
Threads (wait method)
Having doubts about an example from topic Threads in KB.