延迟的ExecutorService

时间:2014-07-20 20:53:21

标签: java concurrency future executorservice

是否有ExecutorService允许我在没有开始执行的情况下提交任务,直到我提出要求为止?我正在寻找像ScheduledExecutorService这样的东西,除了我想手动触发执行而不依赖于固定的时间延迟。

我正在寻找这个的原因是因为我想创建一组任务,这些任务可以递归地使用同一组中并行任务生成的Future的结果。所以我需要先提交所有任务才能得到一组Future,然后才能让任务开始执行。

2 个答案:

答案 0 :(得分:1)

这听起来像是CompletableFuture

的工作
  • 将第一部分任务执行为separe CompletableFutures
  • 然后使用CompletableFuture.allOf(...furures)创建一个仅在完成所有操作后才能完成的屏障未来
  • 然后使用像CompletableFuture.thenAccept这样的组合之一来安排完成障碍未来的下一部分任务

但使用它的更惯用的方法是根据前一个任务的未来结果链接每个下一个任务

CompletableFuture<FirstResult> firstTask = //....
CompletableFuture<SecondResult> secondTask = firstTask.thenApply(someTransformation);
CompletableFuture<Void> anotherTaks = firstTask.thenAccept(someConsumer);
CompletableFuture<ThirdResult> combined =  firstTask.thenAcceptBoth(secondTask, someFunction);

答案 1 :(得分:0)

或许另一种方法是简单地使用FutureCallbackAsyncFunction

FutureCallback示例:

final List<ListenableFuture<T>> futures = new ArrayList<ListenableFuture<T>>();
final Callable<T> callable = new Callable<T>() {
    // Some task you want to complete
};
// Submit all your tasks for execution
futures.add(listeningExecutorService.submit(callable));
// ... add as many tasks as you have
futures.add(listeningExecutorService.submit(callable));

// Get a single Future to wait on
final ListenableFuture<List<T>> future = Futures.allAsList(futures);

Futures.addCallback(future, new FutureCallback<List<T>>() {
    @Override
    public void onSuccess(final List<T> result) {
        // Begin other tasks using `result` (the set of results from the first tasks)
    }
    @Override
    public void onFailure(final Throwable t) {
        // ...
    }
});

如果您不在乎等待完成第二组任务,这将会很有帮助,因为Futures.addCallback没有返回任何内容。

AsyncFunction示例:

final ListenableFuture<O> result = Futures.transform(future, new AsyncFunction<List<T>, O>() {
    @Override
    public ListenableFuture<O> apply(final List<T> input) {
        // Begin other tasks using `input` (the set of results from the first tasks)
    }
});

如果您想等待结果ListenableFuture,或者可能添加第二组完成后需要发生的第三组任务,这将是有益的。

相关问题