Java后台线程Daemon

来源:互联网 发布:四级行政区划数据 编辑:程序博客网 时间:2024/05/29 12:28

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);}}/*outputAll daemons startedThread[Thread-3,5,main] SimpleDaemon@1db05b2Thread[Thread-4,5,main] SimpleDaemon@76fba0Thread[Thread-2,5,main] SimpleDaemon@530cf2Thread[Thread-1,5,main] SimpleDaemon@1175422Thread[Thread-0,5,main] SimpleDaemon@181ed9e */


0 0
原创粉丝点击