守护线程的简单测试

package t1;

public class TestThread {

public static void main(String[] args) {

boolean isDaemon = args.length != 0;// 守护线程会等待最后一个非守护线程结束而死亡
Runnable r = new Runnable() {
public void run() {
Thread thread = Thread.currentThread();
while (true)
System.out.printf("%s is %s alive and in %s state%n",
thread.getName(),
thread.isAlive() ? "" : "not",
thread.getState());

}
};

Thread t1 = new Thread(r, "th1");
if (isDaemon)
t1.setDaemon(true);
System.out.printf("%s is %s alive and in %s state%n",
t1.getName(),
t1.isAlive() ? "" : "not",
t1.getState());

Thread t2 = new Thread(r);
t2.setName("th2");
if (isDaemon)
t2.setDaemon(true);
System.out.printf("%s is %s alive and in %s state%n",
t2.getName(),
t2.isAlive() ? "" : "not",
t2.getState());
t1.start();
t2.start();
}
}

输出结果:

 

posted @ 2020-03-26 15:00  工设091  阅读(151)  评论(0)    收藏  举报