• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Bear Bibeault
  • paul wheaton
Saloon Keepers:
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Mikalai Zaikin
  • Piet Souris
Bartenders:

notify() question from Nikos

 
Ranch Hand
Posts: 252
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

This is a question from Niko's on Threads. What is the result of the following code:


The possible choices are:
a. It prints 0.
b. It prints 999999.
c. The output is not guaranteed to be any of the above.

The answer is choice b.

But b is guaranteed only if line 1 executes before line 2 and the main thread gets the lock on thread object BEFORE the second thread. That cannot be guaranteed. If the reverse happens & line 2 executes first, the program will basically hang at thread.wait() [since notify() has already happened, and wait() doesn't know that].

So shouldn't the answer be choice c?
 
Sheriff
Posts: 9703
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Seems a valid reason to me. To get a guaranteed behavior, the thread.start() statement should be inside the synchronized block in main method...
 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Taken from K & B (SCJP 1.6) page no.: 748 and 749:

This program contains two objects with threads: ThreadA contains the main
thread and ThreadB has a thread that calculates the sum of all numbers from 0
through 99. As soon as line 4 calls the start() method, ThreadA will continue
with the next line of code in its own class, which means it could get to line 11
before ThreadB has finished the calculation. To prevent this, we use the wait()
method in line 9.

Even it is stated that "As soon as line 4 calls the start() method, ThreadA will continue with the next line of code in its own class...". What I do not understand is, how can we be so sure?
 
For my next trick, I'll need the help of a tiny ad ...
Low Tech Laboratory
https://www.kickstarter.com/projects/paulwheaton/low-tech-0
reply
    Bookmark Topic Watch Topic
  • New Topic