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();
}
}
输出结果:
原文:https://www.cnblogs.com/dengw125792/p/12574530.html