中断并行流执行 [英] Interrupt parallel Stream execution

查看:287
本文介绍了中断并行流执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

Thread thread = new Thread(() -> tasks.parallelStream().forEach(Runnable::run));

任务是应该并行执行的Runnable列表。
当我们启动这个线程并开始执行时,根据一些计算,我们需要中断(取消)所有这些任务。

tasks are a list of Runnables that should be executed in parallel. When we start this thread, and it begins its execution, then depending on some calculations we need to interrupt (cancel) all those tasks.

中断线程只会停止其中一个执行。我们如何处理他人?或者Streams不应该那样使用?或者你知道一个更好的解决方案吗?

Interrupting the Thread will only stop one of exections. How do we handle others? or maybe Streams should not be used that way? or you know a better solution?

推荐答案

你实际上并没有在你正在创建的线程上运行Runnables。您正在运行一个将提交到池的线程,因此:

You aren't actually running the Runnables on the Thread you are creating. You are running a thread which will submit to a pool, so:

Thread thread = new Thread(() - > tasks.parallelStream( ).forEach(Runnable :: run));

在这个例子中,你用较小的术语做

In this example you are in lesser terms doing

List<Runnable> tasks = ...;
Thread thread = new Thread(new Runnable(){
    public void run(){
       for(Runnable r : tasks){
          ForkJoinPool.commonPool().submit(r);
       }
    }
});

这是因为你使用的是 parallelStream 在处理并行执行时委托给公共池。

This is because you are using a parallelStream that delegates to a common pool when handling parallel executions.

据我所知,你无法通过<$ c来处理正在执行任务的线程$ c> parallelStream 所以可能运气不好。你总是可以做一些棘手的事情来获得这个线程,但这可能不是最好的主意。

As far as I know, you cannot get a handle of the Threads that are executing your tasks with a parallelStream so may be out of luck. You can always do tricky stuff to get the thread but probably isn't the best idea to do so.

这篇关于中断并行流执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆