Source Address: https://github.com/nieandsun/concurrent-study.git
1 Introduction to the concept daemon thread
Daemon (daemon) thread is a type of thread support, it is primarily used as back-end scheduling and supportive work program. When non-Daemon thread does not exist in a Java virtual machine, Java Virtual Machine exits.
By calling Thread.setDaemon (true) Daemon thread to thread. We generally do not have access, such as garbage collection thread is Daemon thread.
2 daemon thread sample code and Notes
- Test code:
package com.nrsc.ch1.base;
/**
* 类说明:守护线程的使用
*/
public class DaemonThread {
private static class UseThread extends Thread {
@Override
public void run() {
try {
while (!isInterrupted()) {
System.out.println(Thread.currentThread().getName()
+ " I am extends Thread.");
}
System.out.println(Thread.currentThread().getName()
+ " interrupt flag is " + isInterrupted());
} finally {
//守护线程中finally不一定起作用
System.out.println(" .............finally");
}
}
}
public static void main(String[] args) throws InterruptedException {
UseThread useThread = new UseThread();
useThread.setDaemon(true);
useThread.start();
Thread.sleep(1);
//useThread.interrupt();
}
}
- When useThread non-daemon threads
- useThread is daemon thread:
We can see by the above tests
- The main thread ends, a daemon thread will come to an end - "non-daemon threads do not
- finally there is the guardian of the thread may not be performed