Above code prints undetermined number of "going ard in loops" as the output. Can anyone explain this behavior. Also, does theThread=null; actually terminates the thread. As per my understanding, it should not terminate and it will continue executing indefinately even if main thread ends.
Pls do note that Thread behaviour is never consistent in the sense that it depends on a hell a lot of factors.
The code snippet that you provided will terminate if the MAIN thread gains control and invokes the terminate method. Once the terminate method completes, the MAIN thread completes execution as there is no more code left in the main method. Now, when the WORKER thread gains control, the condition in the while loop becomes false and so the WORKER thread also completes its execution and the program terminates GRACEFULLY.
I ran your code snippet in Eclipse 3.1 IDE over the Windows XP Professional OS and the program terminated gracefully after 'going ard in loops' for 20 odd times :-D
Originally posted by Mayank Keshari: In the main program u r making the main thread to relinquish the control, and the run method of the newly created thread contains the infinite while loop. So control never comes to main program.
As I said earlier, the behaviour of Threads is highly unpredictable. You can never say for sure that the MAIN thread will never gain control. Invoking the yield() method doesnt take the MAIN thread out of contention. It MIGHT gain control again. Yeah, It happened in my case
I understand the focus of your question, but I could not help noticing that the object "theThread" does not have a run method! (it does not belong to a class that extends Thread and overrides run). The run method with the print statement belongs to Worker (that implements runnable), but that does not get invoked because there is no w.start() statement. So, if this example were executed as-is, there would be no output at all.
I agree with Arvind in the sense that the behavior of the code is highly unpredictable as we are not sure which out of the two threads (main or theThread) will gain control and at what time.
My real doubt was whether theThread = null stops thread from running altogether. This doubt is however clear now as I understand its not the statement theThread = null in itself that is causing the termination of the thread, it is actually the condition (theThread==Thread.currentThread()) in the while loop that evaluates to false as soon as theThread becomes null. Hence, program terminates gracefully rather than going in an infinite loop. No of rows printed is still unpredictable as we don't know exactly when control will transfer from theThread to main which sets theThread to null and when control is transfered back to theThread, condition fails and program ends.
SCJP 1.4 - 95%
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop