首页 > 解决方案 > ForEach 循环中断和加入线程

问题描述

有一个ArrayList<Wheel>轮子,作为 Wheel 一个扩展Thread的类,如果我有以下情况会发生什么:

wheels.forEach(a -> {
                try{
                    a.interrupt();
                    a.join();
                }catch(InterruptedException exception){}
            });

此代码的指令顺序是什么?

现在我认为它将进行以下操作:1)a被中断,2)我的线程将加入a,并且只有在 a完成后,forEach 循环才会继续通过剩余的项目,对吗?

是否可以在 ArrayList 中进行迭代,其中所有线程都将被中断和加入,而无需手动逐项进行?

非常感谢你的帮助!

标签: javamultithreadingforeach

解决方案


约翰尼的评论对于您当前的实施是正确的。您也可以遵循另一条路径,例如;

您可以在 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));

推荐阅读