gpt4 book ai didi

java - java中线程setDeaemon的困惑

转载 作者:行者123 更新时间:2023-12-01 19:18:01 24 4
gpt4 key购买 nike

根据java当setDaemon设置为true时

it does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.

从下面的代码示例中,当setDaemon设置为true时,主线程创建的线程停止执行,实际上它应该继续运行。当setDaemon设置为false时,即使主线程退出,子线程也会打印i的值。请澄清我的疑问。

public class DeamonSample implements Runnable
{
public void run()
{
try
{
System.out.println("T1 started...");

for (int i=0;i<1000;i++)
{
TimeUnit.SECONDS.sleep(1);
System.out.print(i+" ");
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
System.out.println("T1 ended...");
}

}


/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("Main Started...");
System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
DeamonSample deamonSample=new DeamonSample();
Thread t1=new Thread(deamonSample);
t1.setDaemon(true);
t1.start();
System.out.println("T1 Type="+t1.isDaemon());
System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
System.out.println("Main ended...");
}

}

最佳答案

默认情况下线程不是守护线程。如果您使用任何不是守护进程的线程到达主程序的末尾,那么该进程将继续运行。通过调用 setDaemon(true),您可以告诉 JVM 您的线程不应在 main 结束时阻止关闭。

关于java - java中线程setDeaemon的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5713502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com