本来我是想如果执行时间超过了多久,用线程组的destroy 结束不了。执行threadGroup1.destroy();
报错,Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.ThreadGroup.destroy(ThreadGroup.java:750)
怎么才能结束线程组。while (true) {
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} // 如果 时间超过30分钟自动停止
if ((System.currentTimeMillis() - beginTime) >= ConstantUtil.DURATIONTIME) {
if (threadGroup1.activeCount() > 0) {
threadGroup1.destroy();
}
break;
}
if (threadGroup1.activeCount() == 0) {
endTime = System.currentTimeMillis();
break;
} }
报错,Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.ThreadGroup.destroy(ThreadGroup.java:750)
怎么才能结束线程组。while (true) {
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} // 如果 时间超过30分钟自动停止
if ((System.currentTimeMillis() - beginTime) >= ConstantUtil.DURATIONTIME) {
if (threadGroup1.activeCount() > 0) {
threadGroup1.destroy();
}
break;
}
if (threadGroup1.activeCount() == 0) {
endTime = System.currentTimeMillis();
break;
} }
2)可用ThreadGroup.interrupt()中断线程组中的所有线程,相当于对线程组中所有线程调用interrupt方法;
没有用ThreadGroup.interrupt(),这个我早就用过了,java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.mstar.meds.test.TestThread.run(TestThread.java:28)
at java.lang.Thread.run(Thread.java:595)
TestThread我写了一个while true在那一直跑,本来想通过threadGroup1 来结束时有的线程
public void run() {
while (true) {
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sssstest===");
} }
而你所说的线程中interrupt方法来中断线程,那是错误的,他只是将阻塞的线程打断,抛一个异常而已,并不能够中断线程所谓中断线程的方法,最好的一种方式就是让线程执行完成,线程自然会中断
2)ThreadGroup.destroy(),是直接在这里抛异常,没有正确执行了;
3)catch到InterruptedException异常,你就必需跳出循环,让线程自然终止,因为InterruptedException异常就表示本线程的interrupt方法本调用了,有人希望这个线程终止;
而不是单单的抛出,其实线程很多情况下用interrupt方法来唤醒线程,而不是关闭线程
不过你说的也不错,抛出异常也能够达到线程关闭的作用
改变变量值为false就线程关闭