This is in response to Paul.
Sorry to keep the posts coming but I'm still in the dark so I'm afraid that I need to keep beating the proverbial dead horse here.
Quoting Paul Somnath:
JVM decides that the worker thread runs first. In this case, the thread sleeps (may not sleep!, depends on JVM) but lets assume it sleeps. Then in gets printed first.
I don't know how to reconcile this statement with the statement from K&B 1.5 pg 699.
sleep() is guaranteed to cause the current Thread to stop executing for at least the specified sleep duration.
These two statements seem contradictory. If sleep() is guaranteed to cause the current Thread to go into the waiting/blocking/sleeping state for 2 seconds - how can a JVM choose to ignore it?
Paul, you say,
"In this case...the Thread [t] sleeps... Then in gets printed first"
But that doesn't make sense to me. The Thread t is the thread that prints "in". If it gets put to sleep how can this mean that "in" will be printed first? Doesn't t getting put to sleep suggest the opposite, that Thread main will jump in an print "pre"?
I have been banging my head on this one for a couple of days so please forgive my verbosity, but this is driving my crazy. I have put together a scenario that I think might explain the "in pre post". Somebody please put me out of my misery and either confirm it or rip it to shreds!
"in pre post" Scenario: The main Thread must run first. When the statement
is encountered, the JVM selects the Thread t to be executed first. It then encounters the
call. K&B 1.5 pg 699 says that sleep() is guaranteed to cause the current Thread to stop executing for at least the specified sleep duration. According to this guarantee, the Thread MUST stop executing for 2 seconds.
(Now this is where the part that is hard to believe happens.) Under some implementation of the JVM, though there are only 2 Threads and one of them is asleep, as part of the no guarantees clause, we cannot say for certain that the main Thread will get a chance to execute at all during the 2000 millisecond period that Thread t spends in the waiting/blocking/sleeping state.
In order for "in" to precede "pre", the main thread just sits in the runnable pool for 2000+ milliseconds while Thread t sleeps. Thread t then awakens, joins the Runnable pool and is selected to enter the Running state. Thread t prints "in"...
Is this scenario actually possible? Can a JVM choose to ignore a call to sleep, or is sleeping guaranteed? Can a JVM choose to sit idly while there is a Runnable Thread (like main) waiting in the pool?
Any specific help would be greatly appreciated.