This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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.
Joined: Oct 04, 2008
Thank you Ruben, for the clear answer it makes a lot of sense now.
From exercise 13.6 and also 13.8 from the book, and your explanation it is clear that just calling the run() method does not actually start the thread.
The thread will only be started asynchronously after calling start() on the thread, otherwise just calling the run() method is like invoking any other method.
Joined: Dec 16, 2008
I can see from your explanation that you understand it perfectly, Rashmi.