Hi guys,
Someone wrote me this about threads:
"Thread running depends on the VM Scheduler and there is NO guaranteed a Thread will run and pick by the VM Scheduler despite you have started the Thread with a call x.start(). When you started the Thread it's just in a RUNNABLE STATE, reread the chapter until you fully understood"
(Chapter 9
Thread - Sun Certified Programmer for
Java 6 - Study Guide (310-065) - Kathy Sierra and Bert Bates - 2008)
It is the red sentence that make me really confused. Actually, I read that chapter several times, and I could not read this kind of affirmation in all the chapter. What I could read is this,
From the book (pages 713 and 714)
And the authors wrote this:
Nothing is guaranteed in the preceding code EXCEPT this:
Each thread will start, and each thread will run to completion.
I try to explain myself, what I understood from the sentence in the book:
Each thread will start, and each thread will run to completion
$java ManyNames
After this call, main method from the class ManyNames is invoked and the JVM execute the code in that method sequentially. When the main thread calls one.start(), the one thread (Java thread) is mapped with an Operative System thread (well, in most implementations), but the important thing, the one thread (Java thread) gets the RUNNABLE state waiting for a chance to get the RUNNING state an start the execution of the run() method of its target Runnable. So, at this point we have two thread that can be chosen to get the RUNNING state, main thread and the thread one. Assume main thread executes main method to the end. In this case, the calls two.start() and three.start() are invoked. Main thread finishes, and we have three alive threads waiting for its turn to get the RUNNING state. For me run to completion means that all these threads will print three times the sentence:
"Run by [THREAD NAME: Fred, Lucy or Ricky], x is [1, 2 or 3]"
And all of them will finish their run() method (AS THE CODE STANDS). One possible output could be:
Run by Fred, x is 1
Run by Lucy, x is 1
Run by Lucy, x is 2
Run by Fred, x is 2
Run by Lucy, x is 3
Run by Fred, x is 3
Run by Ricky, x is 1
Run by Ricky, x is 2
Run by Ricky, x is 3
But this order is not guaranteed.
So, my question is simple, if we execute THIS CODE (without any changed) in ANY Java Virtual Machine, is it GUARANTEED that all started threads (main thread, Fred, Lucy and Ricky) will run to completion OR I have to believe what the guy wrote me:
there is NO guaranteed a Thread will run and pick by the VM Scheduler despite you have started the Thread with a call x.start()?
If what this guy said is correct, is it worth create and start a thread if there are not guaranteed that this thread will run to completion? Well, if it is a nice visual clock on the screen it does not matter if we can see the clock or not, but how about if it is a thread that control the emergency process in a factory, just an example.
Thanks for your opinions,
Alvaro