Java多线程系列--“基础篇”10之 线程优先级和守护线程(二)

2014-11-24 03:16:57 · 作者: · 浏览: 4
(isDaemon="+this.isDaemon()+ ")" +", loop "+i);
12 }
13 } catch (InterruptedException e) {
14 }
15 }
16 };
17
18 class MyDaemon extends Thread{
19 public MyDaemon(String name) {
20 super(name);
21 }
22
23 public void run(){
24 try {
25 for (int i=0; i<10000; i++) {
26 Thread.sleep(1);
27 System.out.println(this.getName() +"(isDaemon="+this.isDaemon()+ ")" +", loop "+i);
28 }
29 } catch (InterruptedException e) {
30 }
31 }
32 }
33 public class Demo {
34 public static void main(String[] args) {
35
36 System.out.println(Thread.currentThread().getName()
37 +"(isDaemon="+Thread.currentThread().isDaemon()+ ")");
38
39 Thread t1=new MyThread("t1"); // 新建t1
40 Thread t2=new MyDaemon("t2"); // 新建t2
41 t2.setDaemon(true); // 设置t2为守护线程
42 t1.start(); // 启动t1
43 t2.start(); // 启动t2
44 }
45 }
复制代码
运行结果:
复制代码
main(isDaemon=false)
t2(isDaemon=true), loop 0
t2(isDaemon=true), loop 1
t1(isDaemon=false), loop 0
t2(isDaemon=true), loop 2
t2(isDaemon=true), loop 3
t1(isDaemon=false), loop 1
t2(isDaemon=true), loop 4
t2(isDaemon=true), loop 5
t2(isDaemon=true), loop 6
t1(isDaemon=false), loop 2
t2(isDaemon=true), loop 7
t2(isDaemon=true), loop 8
t2(isDaemon=true), loop 9
t1(isDaemon=false), loop 3
t2(isDaemon=true), loop 10
t2(isDaemon=true), loop 11
t1(isDaemon=false), loop 4
t2(isDaemon=true), loop 12
复制代码
结果说明:
(01) 主线程main是用户线程,它创建的子线程t1也是用户线程。
(02) t2是守护线程。在“主线程main”和“子线程t1”(它们都是用户线程)执行完毕,只剩t2这个守护线程的时候,JVM自动退出。