线程组 destroy 问题

来源:百度知道 编辑:UC知道 时间:2024/07/05 04:14:48
public class Test implements Runnable{
private static java.lang.ThreadGroup threadGroup = null;
public static void main(String[] args) {
threadGroup = new ThreadGroup("thread1");
Thread t = new Thread(threadGroup, new Test());
t.start();

Thread t2 = new Thread(threadGroup, new Test());
t2.start();
threadGroup.destroy();
}

public void run() {
System.out.println("aaaaaaaaaaaaaaaa");

}
}

threadGroup.destroy(); 为什么会报 java.lang.IllegalThreadStateException

destroy() 销毁此线程组及其所有子组。
distroy用于销毁线程组及其子组,但其中的所有线程都必须已经停止执行。
这个我知道
那我应该怎样去停止它的子线程呢

distroy用于销毁线程组及其子组,但其中的所有线程都必须已经停止执行。

有关如何停止一个线程,现在停止线程的stop方法已经不赞成使用,原因jdk文档上写的比较清楚:
<-----------------------
stop()
已过时。 该方法具有固有的不安全性。用 Thread.stop 来终止线程将释放它已经锁定的所有监视器……这有可能导致任意的行为。stop 的许多使用都应由只修改某些变量以指示目标线程应该停止运行的代码来取代。目标线程应定期检查该变量,并且如果该变量指示它要停止运行,则从其运行方法依次返回。如果目标线程等待很长时间(例如基于一个条件变量),则应使用 interrupt 方法来中断该等待。
----------------------->

也就是说,你要么等待每个线程自行结束(run方法自然返回),要么在其中通过设置标识变量,并让线程通过定期检查该变量以确定是否应该中途返回。