1 package com.xt.thinks21_2;
 2 
 3 import java.util.concurrent.TimeUnit;
 4 
 5 /**
 6  * 后台线程测试
 7  * 
 8  * @author Administrator
 9  *
10  */
11 public class SimpleDaemonTest implements Runnable {
12 
13     @Override
14     public void run() {
15         // TODO Auto-generated method stub
16         while (true) {
17             try {
18                 TimeUnit.MILLISECONDS.sleep(100);
19                 System.out.println(Thread.currentThread() + ":" + this);
20             } catch (InterruptedException e) {
21                 // TODO Auto-generated catch block
22                 e.printStackTrace();
23             }
24         }
25     }
26 
27     public static void main(String[] args) {
28         for (int i = 0; i < 10; i++) {
29             Thread t = new Thread(new SimpleDaemonTest());
30             t.setDaemon(true);// 设置为后台线程,如果不设置则为非后台线程,会无线打印线程信息
31             t.start();
32         }
33         System.out.println("ALL DEAMON IS START!");
34         try {
35             TimeUnit.MILLISECONDS.sleep(175);// 175>100,所有每个线程信息打印一次
36         } catch (InterruptedException e) {
37             // TODO Auto-generated catch block
38             e.printStackTrace();
39         }
40     }
41 
42 }

后台线程与非后台线程的方法区别:后台线程会主动设置Thread.setDeamon(true)

当非后台线程结束时,后台线程强制结束