- import static java.util.concurrent.TimeUnit.*;
- public class DaemonTest {
- public static void main(String[] args) throws InterruptedException {
- Runnable r = new Runnable() {
- public void run() {
- for (int time = 10; time > 0; --time) {
- System.out.println("Time #" + time);
- try {
- SECONDS.sleep(2);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- };
- Thread t = new Thread(r);
- t.setDaemon(true); // try to set this to "false" and see what happens
- t.start();
- System.out.println("Main thread waiting...");
- SECONDS.sleep(6);
- System.out.println("Main thread exited.");
- }
- }
当t.setDaemon(true),即t为Daemon线程时,执行结果如下:
t为Daemon线程的输出:
Time #10
Time #9
Time #8
Main thread exited.
Time #7
当t.setDaemon(false),即t为非守护线程时,执行结果如下:
Main thread waiting...
Time #10
Time #9
Time #8
Main thread exited.
Time #7
Time #6
Time #5
Time #4
Time #3
Time #2
Time #1
总结: 1、当主线程一结束、(非守护线程的)子线程不会立即结束。 2、当主线程一结束,(守护线程的)子线程会立即结束。 3、子线程对象,在调用start()方法之前,通过调用setDaemon(true),将本子线程设置为守护线程。