Like in this case I created one new thread and made it daemon thread by setDaemon(true). After initializing the Daemon thread the main exits, the daemon thread continues to execute.
Now I tried putting sleep(500) in the run method.Then it exits.
so what i conclude from this is that even if the main thread dies, the daemon thread remains active and continues to execute for a certain period of time only then dies. Now it depends if your code is small it might get executed completed else it might execute only partially. But there is not guarantee.
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
* The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place. * All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
Thanks for posting the code. I ran it without the sleep. Yes, it does look as if the started thread does get some time to run, but it does not always run to completion - it terminates during the loop when it gets whatever signal is sent to it when the JVM detects that the main thread dies. The behaviour is as expected.