I'm trying to understand the outcome of Exercise 13.6 posted in the sample chapter on Threads in the A Programmer's Guide to JavaSCJP Certification - 3rd Edition
The output I get is that R2 is printed twice and R1b is printed once. I don't understand why R2 is being printed twice (instead of just once).
From logically thinking about the outcome, it appears that R2 is printed once (when the thread starts the first time, which invokes R2's run() asynchronously at some point)
then what causes R2 to be printed again?
Is it because of this line? :
because the code in the sample never called new Thread(new R1(),"|R1a|").start() , so the R1 thread will never start running.
so calling the run() method manually in R1 , is just that (it is not a thread execution) , so the current thread it prints is R2 ?
1. Thread in main() starts new thread with target R2 and name |R2|.
2. Thread |R2| creates a new Thread object with target R1 and name |R1a|. Then, thread |R2| executes the run() method of that Thread object (howevere this doesn't start the thread of execution |R1a|, so the run() in R1 will be run under the current thread, which is |R2|.) This accounts for one |R2| output.
3. Thread |R2| creates a new Thread object with target R1 and name |R1b|, and starts this new thread. Ultimately this will cause the run() method in R1 to be called for thread |R1b|, which accounts for one |R1b| output.
4. The code System.out.print(Thread.currentThread().getName()); is executed under thread |R2|, which accounts for another |R2| output.
5. In total, we have two |R2| outputs and one |R1b| output. Output for |R1a| is never created, since that thread is never started.
All code in my posts, unless a source is explicitly mentioned, is my own.