1. output could be r1 r2 m1 m2
2. output could be m1 m2 r1 r2
3. Ouptut oculd be m1 r1 r2 m2
4. Output could be m1 r1 m2 r2
I figure option 1 could be true because when main executes t.start(), the JVM could schedule t right away, and it could run to completion, but the book says that is not a valid answer ??
Hello Rahel. I read your question and also simultaneously read the same example from KB book and i found that, the option 1 as per your given question is a valid answer along with option 3 provided, if the join() is placed inside a try/catch block which i guess you have already done on line 8. I would ask you go through the same code once again to clarify your doubt. But, one thing i couldn't figure out that, why is there a second t.join() on line 10? I feel it is unnecessary and neither could i spot the same in the example from KB book
sarvesh dikonda wrote:Hello Rahel. I read your question and also simultaneously read the same example from KB book and i found that, the option 1 as per your given question is a valid answer along with option 3 provided, if the join() is placed inside a try/catch block which i guess you have already done on line 8. I would ask you go through the same code once again to clarify your doubt. But, one thing i couldn't figure out that, why is there a second t.join() on line 10? I feel it is unnecessary and neither could i spot the same in the example from KB book
Hope this helps!
Sorry, I had a mistake in the code I posted, and the second t.join() should not be there. Here is the updated example:
SO BACK TO THE BOOK FOR POSSIBLE ANSWERS:
r1 r2 m1 m2
1.Main thread executes t.start()
2. JVM runs the t thread just started, and the t thread prints r1 followed by r2
3. the t thread finishes its' run function
4. the main thread executes t.join(), but I guess it will wait forever at this point since t is already completed executing ?? BUt the book is saying that this is a possible valid answer ??
m1 m2 r1 r2
I can see in this example that m2 can never get printed before r1 and r2 because of the t.join() statement
m1 r1 r2 m2
1.Main thread executes t.start()
2. Main thread prints m1
3. Main thread executes t.join
4. JVM schedules the t thread
5. the t thread prints r1 and r2
6. The main thread then prints m2
So yes, this is a valid option
m1 r1 m2 r2
again in this scenario, m2 can never be printed before r2
Hello Rachel in Threads the output is never guaranteed to be the same way always. It is dependent upon the Thread Scheduler. And for the output r1 r2 m1 m2, the statement in point 4 that you made is not acceptable as, the thread 't' does not wait endlessly if that thread has completed executing run(). It simply proceeds further down the code causing no error.
Post by:autobot
The City calls upon her steadfast protectors. Now for a tiny ad:
a bit of art, as a gift, that will fit in a stocking