Thank you Vad for reading my post. I like to share what I am learning. It is nice to know I am not talking to myself.
but if it's like any other thread, then the output may differ. The second question: will the overall behaviour remain the same if main() completes first?
Yes, the output may differ.
My output only shows one case. It shows what I would call the worst case. It shows that IF the new thread throws an exception early on, the main thread will continue with its business, sleeping and printing its name.
We might not want to generalize from one case. But this one case does demonstrate the general (overall) behavior/behaviour stated in TJPL.
If
Java would print time in microseconds, we could get a better idea of what happens when. Milliseconds are just not very informative.
---- Just more boring details ...
When the main thread invokes start() and even before start() returns, the scheduler can choose to execute the new thread or continue executing the main thread.
So one possibility is the run() method is executed first. The new thread prints its name, throws an exception and dies. Then the main thread sleeps for 3 seconds, prints its name and dies.
Another possibility is the main thread sleeps for 3 seconds. Maybe in those three seconds, the Java virtual machine is swapped out and the underlying operating system executes other processes. The main thread completes, then the new thread executes run().
Another possibility is some byte codes of the main thread are executed, then some byte codes of the new thread are executed, the some more byte codes of the main thread are executed, et cetera.
Another possibility is both threads begin to run simultaneously in two different CPUs. The main thread sleeps and the new thread throws an exception in parallel.
I suspect what actually happened (the typical behavior/behaviour on my system) is that start() returned and the main thread invoked sleep. Then the new thread executed run() completely. On my system, after invoking start(), the main thread doesn't easily give up unless I add a Thread.yield().
[ October 06, 2003: Message edited by: Marlene Miller ]