对于“后台线程创建的子线程默认是后台线程”这句话做了如下的验证:
public class DaemonThread extends Thread
{
Thread dt = new Thread("哈哈");
@Override
public void run()
{
//这里输出的是false
System.out.println(dt.isDaemon());
for (int i = 0; i < 1000; i++) {
System.out.println(getName() + " " + i);
}
}
public static void main(String[] args)
{
DaemonThread t = new DaemonThread();
t.setDaemon(true);
t.start();
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}
上面注释的地方输出的是 false;而下面的代码:
public class DaemonThread extends Thread
{
@Override
public void run()
{
Thread dt = new Thread("哈哈");
//这里输出的是true
System.out.println(dt.isDaemon());
for (int i = 0; i < 1000; i++) {
System.out.println(getName() + " " + i);
}
}
public static void main(String[] args)
{
DaemonThread t = new DaemonThread();
t.setDaemon(true);
t.start();
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}
上面注释的地方输出的是true,
这两段代码,求大神指点不同之处,谢谢!最好能把“前台线程创建的子线程的子线程默认就是前台线程,后台线程创建的子线程默认是后台线程”这句话解释一下,不胜感谢!
------解决方案--------------------
对于第二段代码中,正好说明了“后台线程的子线程默认是后台线程”这句话,因为在main线程中创建了DaemonThread?对象,设置为守护线程后启动该线程,在DaemonThread?中的run()方法中,再次创建了一个Thread对象的线程,所以,Thread对象也是守护线程。