Thursday, February 10, 2011

Conceptual Question About Java Concurrency

If I I have a class whose run() method sleeps for 1000 ms and then print "Thread". And I start this thread from my main program, then have my main program immediately sleep for 2000 ms, and then print "Main Thread".

Is it guaranteed that Thread will be printed before Main Thread?

  • Nope. Conceptually, it's possible that the system you're running on will be so busy that the new thread doesn't even get a chance to run anything before the main thread has had a chance to sleep and print "Main Thread". In reality that's very unlikely, of course, but fundamentally sleep is not a coordination primitive.

    S.Lott : +1: sleep has no guarantees at all. It may not even sleep for the requested time because it could get interrupted.
    Peter Lawrey : In which case, it is not guaranteed that either message will be printed at all. ;)
    From Jon Skeet

0 comments:

Post a Comment