Daemon Threads in Java
The daemon thread in Java differs from the concept of a daemon thread in Unix, where the daemon thread in UNIX is the equivalent of a service, running in the background, and the daemon thread in Java is defined like this:
A daemon thread is a thread, which does not prevent the JVM from exiting when the program finishes but the thread is still Running.
That is, the JVM automatically exits when there is only a daemon thread in the program, and a typical daemon is the garbage collector (GC).
When we create a new thread, it inherits the state of its parent thread's daemon, that is, if its parent thread is the daemon thread, its child threads are also the daemon threads.
The difference between a daemon thread and a normal thread is that the JVM does not exit if it is not finished, the daemon is not the same, when the normal thread is complete and the daemon is not finished, the JVM discards the remaining daemon threads and exits the virtual machine directly, so the i/ o The associated operation cannot be given to the daemon to operate.
Let's look at an example:
PackageCom.test;/** * Created by z1178 on 2015-08-09. * * Public class MyTest { Public Static void Main(string[] args) {NewWorkerthread (). Start ();Try{Thread.Sleep (7500); }Catch(Interruptedexception e) {System.out.println ("Main thread ending"); }}}class Workerthread extends thread{ Public Workerthread() {Setdaemon (true); } Public void Run(){intCount=0; while(true) {System.out.println ("Hello from Worker"+count++);Try{Sleep ( the); }Catch(Exception e) {E.printstacktrace (); } } }}
If we set Setdaemon to True or false, it will wait for a different result, if true, the result is as follows:
Hello from Worker 0
Hello from Worker 1
Indicates that when the main thread executes, the JVM exits, and if Setdaemon is set to false, it will continue to execute and the JVM will not exit.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Daemon Threads in Java