gpt4 book ai didi

java - 如何正确关闭所有线程?

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

我有 8 个线程,每个线程在它们的 run 方法中执行与此类似的循环:

for (int i = 0; i < someVar; i++) {
for (int j = 0; j < someOtherVar; j++) {
if (Thread.currentThread().isInterrupted()) {
return;
}
// another loop and some calculations here
}
}

我这样启动线程:

 executor = Executors.newFixedThreadPool(threads);

// generate the threads and run them
for (int i = 0; i < threads; i++) {
MyClass cls = new MyClass(i);
executor.execute(cls);
}

现在我需要能够立即终止我的线程,这就是我在上面添加 if 语句并在另一点使用 executor.shutdownNow() 的原因。但它的工作速度不够快。某些计算可能需要几秒钟才能完成并开始下一次迭代。

有没有其他可靠的方法几乎可以立即关闭线程?

最佳答案

您需要调用线程并停止当前执行的中断操作。这是一些文档:http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

关于java - 如何正确关闭所有线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23299051/

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