本文介绍了与另一个任务并行运行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Foo 类,它使用 FooProcessor 类。所以我想要做的是,在运行cp1实例进程方法的同时,我要运行 cp2.process()

I have the following Foo class that uses FooProcessor class. So what i want to do is, while running cp1 instance process method, in parallel I want to run cp2.process().

public class Foo {

    public static void main(String [] args){

        FooProcessor cp1 = new FooProcessor();
        FooProcessor cp2 = new FooProcessor();

        cp1.process();
        // in parallel process cp2.process();
    }

}

public class FooProcessor {
    public void process(){
        System.out.println("Processing..");
    }
}

但是,我想要顺序cp1,所以我想要它运行和完成,如果cp2没有完成或失败,它是好的。如果它失败了我想加入结果。它没有返回此示例中的任何内容,但我想返回结果。

However, i want cp1 sequentially, so i want it to run and complete, if cp2 doesnt complete or fails it is fine. If it doenst fail i want to join the results. It is not returning anything in this sample but I want to return result.

为此目的,应该使用TaskExecutor吗?或线程?

For this purpose, should is use TaskExecutor? or Thread?

我只希望cp2与cp1并行运行。或者如果我添加更多让我们说cp3,我希望它也能并行运行到cp1。

I want only cp2 to run in parallel to cp1. or if i add more lets say cp3, i want that to run in parallel as well to cp1.

推荐答案

我会这样做总结一下:


  • 通过,例如 ExecutorService executor = Executors.newFixedThreadPool(nThreads);

  • 存储列表中的所有任务(由ExecutorService#submit返回)

  • 等待完成,其中 future1 是未来与cp1相关联的

  • 一旦获取返回(cp1已完成)所有其他期货,(或 shutdownNow 执行者服务,如果您不再需要执行者)

  • 要使取消过程正常工作,您的cp2,cp3等需要实施中断策略,使他们停止他们的正在尽快做。

  • run your different processes via an ExecutorService, for example ExecutorService executor = Executors.newFixedThreadPool(nThreads);
  • store the Futures of all your tasks in a List (returned by ExecutorService#submit)
  • wait for future1.get() to complete, where future1 is the future linked to cp1
  • once get returns (cp1 has finished) cancel all the other futures, (or shutdownNow the executor service if you don't need the executor any longer)
  • for that cancellation process to work, your cp2, cp3 etc need to implement an interruption policy that makes them stop what they are doing asap.

这篇关于与另一个任务并行运行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-11 15:05