java - ForEach 循环中断和加入线程
问题描述
有一个ArrayList<Wheel>
轮子,作为 Wheel 一个扩展Thread的类,如果我有以下情况会发生什么:
wheels.forEach(a -> {
try{
a.interrupt();
a.join();
}catch(InterruptedException exception){}
});
此代码的指令顺序是什么?
现在我认为它将进行以下操作:1)a被中断,2)我的主线程将加入a,并且只有在 a完成后,forEach 循环才会继续通过剩余的项目,对吗?
是否可以在 ArrayList 中进行迭代,其中所有线程都将被中断和加入,而无需手动逐项进行?
非常感谢你的帮助!
解决方案
约翰尼的评论对于您当前的实施是正确的。您也可以遵循另一条路径,例如;
您可以在 Wheel 类中实现 Runnable(或 Callable)并将您的任务列表提交给执行器服务,而不是扩展线程。通过这种方式,您可以获得线程池(重用线程)的好处,并使用关闭和等待所有线程完成的内置功能。
例子:
ExecutorService executor = Executors.newFixedThreadPool(5);
wheels.foreach(wheel -> executor.submit(wheel));
//when you want to shutdown
executor.shutdownNow(); // this will send interrupt to thread pool threads.
executor.awaitTermination(10, TimeUnit.SECONDS);
// block the current thread until executor finishes or timeout expires.
// You could give a bigger timeout or call this with in a while loop to ensure
// executor definitely finished.
// like this: while(!executor.awaitTermination(10, TimeUnit.SECONDS));
推荐阅读
- javascript - 如何从弹出窗口中获取 url?
- android - Android 应用不断显示“应用无响应”错误
- sql - 按条件选择行:a and (b xor c)
- powershell - 我可以更改 Out-GridView 的按钮名称吗?
- node.js - 我如何在 express 中导入 react 。在进行反应服务器端渲染时
- windows - IF 多个条件
- python - glm.project() 函数显示错误,即使参数类型正确
- c++ - atan2 是否需要归一化向量?向量之间的角度使用 acos 或 atan 哪个更好?
- python - 当重定向的 URL 出现 DNS 外观错误时,如何抓取 URL?
- java - java - 如何在java spring中从Long字段的值中删除L