守护线程在创建它的线程结束后会自动结束。
我写了一个小例子,但我发现即使设置成守护线程,但程序在Main函数return之后仍然在运行public class test exte
nds Thread{
private String s;
public test(String s,boolean b){
this.s=s;
setDaemon(b);
}
public void run(){
for(int i=0;i<50;i++){
System.out.println(s+" print "+(i+1)+" times");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}public class SockerServerRun { /**
* @param args
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
test t1 = new test("11111",true);
test t2 = new test("22222",false);
t1.start();
t2.start();
System.out.println("Thread is closed");
return;
}
}
执行之后发现,在main函数推出后,t1和t2对象持续输出,并没有停止。
如果两个线程都设置成守护线程的话,那么在main推出后,两个线程也停止了。这是什么原因,请教大家
我写了一个小例子,但我发现即使设置成守护线程,但程序在Main函数return之后仍然在运行public class test exte
nds Thread{
private String s;
public test(String s,boolean b){
this.s=s;
setDaemon(b);
}
public void run(){
for(int i=0;i<50;i++){
System.out.println(s+" print "+(i+1)+" times");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}public class SockerServerRun { /**
* @param args
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
test t1 = new test("11111",true);
test t2 = new test("22222",false);
t1.start();
t2.start();
System.out.println("Thread is closed");
return;
}
}
执行之后发现,在main函数推出后,t1和t2对象持续输出,并没有停止。
如果两个线程都设置成守护线程的话,那么在main推出后,两个线程也停止了。这是什么原因,请教大家
不知道你有没有写过网页。
假设main线程是网站的主窗口,里面内嵌的子窗口(frame)好比main调用的函数,当main关了,这些frame绝对不会再存在。但是用户线程类似是main用window.open()弹出来的新窗口,main关了,他们还是在的
main函数退出不代表主线程结束吧?
这句话你那里看到的,整个google上,你是唯一的出处。
A daemon thread is simply a background thread that is subordinate to the thread that creates it, so when the thread that created the daemon thread ends, the daemon thread dies with it。这是原话啊?我断章取义了吗,还是理解的有问题。
1 所有线程都结束的情况下
2 剩下的都是daemon
3 调用了System.exit或者其他致命错误
尽信书不如无书!
thanks 蝈蝈
如果剩下的都是daemon线程,jvm退出。
只有t1是守护线程。所以只有在t2和main都结束之后,程序才能退出。“守护线程在创建它的线程结束后会自动结束”,这句话你从哪里看到的,完全错误!
你的t1为true,所以为守护线程你的用户线程一直运行着没有结束,所以你的t1守护线程也一直在跑
因此 连个线程都在跑