package com.yiing.study.thread;
import java.util.concurrent.TimeUnit;
/**
* 后台线程,是指在程序运行的时候在后台提供一种通用服务的线程并且这种线程并不属于程序中
* 不可或缺的一部分。当所有的非后台线程结束时,程序也就终止了,同时会杀死进程中所有后台线程。
* 只要任何非后台线程还在运行,程序就不会终止
* @author Administrator
*
*/
public class SimpleDaemons implements Runnable{
@Override
public void run() {
try{
while(true){
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread() + " " + this);
}
}catch(InterruptedException e){
System.out.println("sleep() intterupted");
}
}
public static void main(String[] args) throws InterruptedException{
for(int i = 0; i<10; i++){
Thread daemon = new Thread(new SimpleDaemons());
daemon.setDaemon(true);
daemon.start();
}
System.out.println("All daemons started");
TimeUnit.MILLISECONDS.sleep(175);
}
}
/**
* 运行结果
* All daemons started
Thread[Thread-4,5,main] com.yiing.study.thread.SimpleDaemons@de6f34
Thread[Thread-8,5,main] com.yiing.study.thread.SimpleDaemons@10d448
Thread[Thread-6,5,main] com.yiing.study.thread.SimpleDaemons@19b49e6
Thread[Thread-0,5,main] com.yiing.study.thread.SimpleDaemons@156ee8e
Thread[Thread-1,5,main] com.yiing.study.thread.SimpleDaemons@47b480
Thread[Thread-2,5,main] com.yiing.study.thread.SimpleDaemons@156ee8e
Thread[Thread-5,5,main] com.yiing.study.thread.SimpleDaemons@12ac982
Thread[Thread-9,5,main] com.yiing.study.thread.SimpleDaemons@1bf216a
Thread[Thread-3,5,main] com.yiing.study.thread.SimpleDaemons@6ca1c
Thread[Thread-7,5,main] com.yiing.study.thread.SimpleDaemons@e0e1c6
*/