主线程结束,其他线程正常运行
public class ParentTest
{
public static void main(String[] args)
{
System.out.println("parent thread begin ");
ChildThread t1 = new ChildThread("thread1");
ChildThread t2 = new ChildThread("thread2");
t1.start();
t2.start();
System.out.println("parent thread over ");
}
}
class ChildThread extends Thread
{
private String name = null;
public ChildThread(String name)
{
this.name = name;
}
@Override
public void run()
{
System.out.println(this.name + "--child thead begin");
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println(e);
}
System.out.println(this.name + "--child thead over");
}
}
程序运行结果如下:
parent thread begin
parent thread over
thread2--child thead begin
thread1--child thead begin
thread2--child thead over
thread1--child thead over
主线程结束,其他守护线程立刻结束
提示: 主线程不能设置成守护线程
public class ParentTest
{
public static void main(String[] args)
{
System.out.println("parent thread begin ");
ChildThread t1 = new ChildThread("thread1");
ChildThread t2 = new ChildThread("thread2");
t1.setDaemon(true);
t2.setDaemon(true);
t1.start();
t2.start();
System.out.println("parent thread over ");
}
}
class ChildThread extends Thread
{
private String name = null;
public ChildThread(String name)
{
this.name = name;
}
@Override
public void run()
{
System.out.println(this.name + "--child thead begin");
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println(e);
}
System.out.println(this.name + "--child thead over");
}
}
执行结果如下:
parent thread begin
parent thread over
thread1--child thead begin
thread2--child thead begin
参考:
https://www.cnblogs.com/qiumingcheng/p/8202393.html