This question is the continuation to it. We can set the spawned threads as daemon thread it means that when the main thread dies all spawned thread should terminate and program should terminate.
in the same code (which i had put previously, if i put the t2 thread as setDaemon(true) then the program output is totally different. I tried to figure out the flow....but it is going out of my scope...
Since the newly created threads (spawned as anonymous threads) now are daemon threads, you would expect them not to print anything but 21 and 11 respectively if they get a chance to run. This is because, due to the join, the first spawned thread waits for the main thread to finish and the second spawned thread waits for the first spawned thread. But, since the main thread finishing implies the termination of the program and thus of all daemon threads, the daemon threads in the given code wouldn't seem to have the chance to invoke the code on line 3 (see code below)
But, the contrary seems true, because by running the code on my machine the two daemon threads get the chance to invoke the code on line 3.
At first sight I thought this was weird: main terminates and daemon threads still produce output But I remembered an issue which might explain this behaviour as well. You know that you can't call the start() method twice on a thread instance with a terminated run() method. Well, if you invoke the start() method a second time while the thread is dying then you will get a runtime error complaining, but if you let the thread die and call start() after sleeping a bit then nothing happens and there is no runtime error. This is because in the former case the dying thread hasn't managed to settle all it's status information.
I believe that in your example the same is happening. The daemon threads just produce output, because the main thread takes longer to change to the dead status when it is actually terminated. If you change the code as follows (the newly spawned threads always sleep for a relatively long period, see line 1 and 2):
then you will see that the daemon threads won't print anything, because the main thread's status settles to dead while the daemons are sleeping and subsequently the daemons are terminated because there is no running non-daemon thread anymore.
Gian Franco [ June 06, 2004: Message edited by: Gian Franco Casula ]
"Eppur si muove!"
Hey cool! They got a blimp! But I have a tiny ad:
ScroogeXHTML - small and flexible RTF to HTML converter library