gpt4 book ai didi

java - JAVA 中的守护进程线程组是什么?

转载 作者:行者123 更新时间:2023-11-30 06:53:32 26 4
gpt4 key购买 nike

我知道线程可以是守护进程也可以是非守护进程。我们可以使用 isDaemon() 方法来检查线程是否是守护进程。 isDaemon() 方法也适用于线程组。

class MyThread extends Thread
{
MyThread(ThreadGroup g, String name)
{
super(g,name);
}
public void run()
{
long i = 0;
for(long l=0; l<999999999; l++)
{
i=i+3;
}
}
}

class Check
{
public static void main(String[] args)
{
ThreadGroup sys = Thread.currentThread().getThreadGroup().getParent();
ThreadGroup parent = new ThreadGroup("parent");
MyThread t1 = new MyThread(parent, "t1");
ThreadGroup child = new ThreadGroup(parent,"child");
Thread t2 = new Thread(child, "t2");
t1.start();
t2.start();
ThreadGroup[] t = new ThreadGroup[sys.activeGroupCount()];
sys.enumerate(t);
for(ThreadGroup ti: t)
{
System.out.println(ti.getName()+" "+ti.isDaemon());
}
System.out.println(sys.getName()+" "+sys.isDaemon());
}

输出:

main  false
parent false
child false
system false

这里System也是一个非守护线程组。线程组如何成为守护进程?我的意思是守护线程组的属性是什么?系统线程组如何非守护?

最佳答案

与Thread方法相同:java.lang.ThreadGroup#setDaemon。当您创建线程组时,您可以将其标记为守护进程。

根据 javadoc:

A daemon thread group is automatically destroyed when its last thread is stopped or its last thread group is destroyed.

关于java - JAVA 中的守护进程线程组是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37431918/

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