【问题标题】:how to stop child threads if exception occurs in any of them from parent thread如果父线程中的任何一个发生异常,如何停止子线程
【发布时间】:2016-06-18 19:14:28
【问题描述】:

我想停止一个没有循环的线程

while(!cancelled) //where cancelled is volatile variable
{
   //
}

不能使用,因为我想在没有循环的情况下执行长时间运行的任务, 如果父线程中的任何一个发生异常,如何停止子线程

@奥利弗

正如 oracle 文档中提到的那样

for (int i = 0; i < inputs.length; i++) {
    heavyCrunch(inputs[i]);
    if (Thread.interrupted()) {
        // We've been interrupted: no more crunching.
        return;
    }
}

在上面的代码中 if() 只会在heavyCrunch(inputs[i]) 完成时调用

【问题讨论】:

标签: java multithreading executorservice


【解决方案1】:

看起来您的目标是中断驱动的应用程序。您可以保留已生成的线程列表,并在异常中遍历其他线程并中断它们。

https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-19
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    相关资源
    最近更新 更多