您的位置:首页 > 编程语言 > Java开发

Java后台线程Daemon

2014-08-30 21:19 267 查看
1、daemon后台线程,是程序运行时在后台提供的一种通用服务线程

2、所有非后台线程结束时,程序终止,同时会杀死所有后台进程。

3、设置后台进程:在程序启动前调用setDaemon()方法。

4、后台进程可能在不执行finally子句的情况下就会终止run()方法。(特例)

import java.util.concurrent.TimeUnit;

public class SimpleDaemon implements Runnable {
public void run(){
try{
while(true){
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread()+" "+this);
}
} catch (InterruptedException e) {
//e.printStackTrace();
System.out.println("sleep() interrupt");
}
}
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<5;i++){
Thread thread=new Thread(new SimpleDaemon());
//设为后台线程
thread.setDaemon(true);
thread.start();
}
System.out.println("All daemons started");
//main睡眠才能看到后台线程的运行结果,睡眠时间太短可能就看不到了
TimeUnit.MILLISECONDS.sleep(175);
}

}
/*output
All daemons started
Thread[Thread-3,5,main] SimpleDaemon@1db05b2
Thread[Thread-4,5,main] SimpleDaemon@76fba0
Thread[Thread-2,5,main] SimpleDaemon@530cf2
Thread[Thread-1,5,main] SimpleDaemon@1175422
Thread[Thread-0,5,main] SimpleDaemon@181ed9e
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: