後臺線程表示的是當前任務中不是必不可少的線程,例如在main線程裏面啓動了一下後臺線程那麼當main線程執行完了過後,不管後臺線程是否執行完畢都會被殺死。
Java中設置線程爲後臺線程的方法是用Thread的setDaemon(true)//Daemon讓我想起了spn裏面的sammy 和dean
示例如下:
package come.afeiluo;
public class DaemonTest implements Runnable {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
System.out.println(Thread.currentThread() + " " + this);
} catch (InterruptedException e) {
System.out.println("sleep interrupted");
}
}
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new DaemonTest());
thread.setDaemon(true);
thread.start();
}
System.out.println("all daemon started");
Thread.sleep(50);//調整這裏main線程裏面的sleep的時間, 觀察輸出的結果
}
}
我們發現當調整sleep裏面的時間的時候發現,輸出的結果也會相應的發生改變
那這是爲什麼呢?這是因爲在main線程裏面啓動了10個後臺線程,當main線程執行完了(代碼最後一行的Thread.sleep也是main線程裏面的)過後後臺線程會自動被殺死,所以main線程等待的時間不同那麼後臺線程執行的時間也就不同,相應的輸出也就不同了