When Java Concurrency in Practice or see Java-related code involves concurrent, often encounter some threads (such as doing statistical metrics thread, etc.) will by setDaemon()
setting the thread's daemon variable is set to True method, that is, this thread In order to set the daemon threads (daemon the thread) , then what is the daemon thread it? Or the difference between non-daemon threads and daemon threads (common thread) in place? This is mainly about the content of this article.
Daemon thread
In general, the Java thread can be divided into two types: ordinary thread and thread guard. When JVM just started, all the threads it creates, in addition to the main thread (main thread), the other thread is a daemon thread (for example: garbage collector, and other secondary action thread).
When you create a new thread, a new thread will inherit the daemon status of its thread, by default, all the threads created by the main thread are common threads.
Under what circumstances would require daemon threads it? Under normal circumstances, when we want to create a secondary thread to perform some work, but do not want to close this thread hinder the JVM, in this case, we need to use a daemon thread.
The role of guardian of the thread
Daemon thread with the common thread is the only difference: when the thread exits, JVM will check other threads running, if these threads are daemon threads, the JVM exits normally operate, but if there are common threads still running, JVM is exit does not perform the operation. When JVM exits, all remains the guardian of the thread will be abandoned, neither part of the implementation of the code finally, it will not perform stack unwound operation, JVM will exit.
When the JVM halts any remaining daemon threads are abandoned: |
Here there is a small example, from the What IS A daemon the Thread in the Java? , Code is as follows:
1 |
public class DaemonTest { |
When the thread is normal, the output is as follows:
Hello from Worker 0 |
In other words, this time even if the main thread of execution is over, JVM will wait WorkerThread finished will quit, and if the thread is a daemon thread set, then output as follows:
Hello from Worker 0 |
在 main 线程执行完毕后,JVM 进程就退出了,不会 care WorkerThread 线程是否执行完毕。
参考: