美文网首页
8-CompletionService

8-CompletionService

作者: 鹏程1995 | 来源:发表于2020-02-11 10:58 被阅读0次

概述

引入

我们在上一节讲invokeAny()时讲到了一个新的接口CompletionService,我们本节对其进行基本介绍。

摘要

由于之前已经对线程池的接口定义意图和意义做了详细的介绍,我们对CompletionService,仅做它多出来几个方法的介绍。

类介绍

类定位

CompletionService可以看作是一个特殊的Executor或者一个特殊的ExecutorService,更具体的来说:他其实只是针对线程池的业务环境,按照自己的口味加了一个完成任务的顺序的队列

我们之前介绍的Executor/ExecutorService的注意力都在任务的执行上,任务执行状态、执行结果的管控都是由返回的Future做的,CompletionService在这点上做了优化。

注意

这个类看用途还是有些用的,但是不知道哪里用到了,后面如果遇到了再回头看。

源码解读

此处只介绍新不同的API:

/**
 * Retrieves and removes the Future representing the next
 * completed task, waiting if none are yet present.
 *
 * @return the Future representing the next completed task
 * @throws InterruptedException if interrupted while waiting
 */
Future<V> take() throws InterruptedException;

/**
 * Retrieves and removes the Future representing the next
 * completed task, or {@code null} if none are present.
 *
 * @return the Future representing the next completed task, or
 *         {@code null} if none are present
 */
Future<V> poll();

/**
 * Retrieves and removes the Future representing the next
 * completed task, waiting if necessary up to the specified wait
 * time if none are yet present.
 *
 * @param timeout how long to wait before giving up, in units of
 *        {@code unit}
 * @param unit a {@code TimeUnit} determining how to interpret the
 *        {@code timeout} parameter
 * @return the Future representing the next completed task or
 *         {@code null} if the specified waiting time elapses
 *         before one is present
 * @throws InterruptedException if interrupted while waiting
 */
Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException;

也没什么特别的东西,像是在线程池的基础上加入了一点阻塞队列的东西。

使用思路

在你需要子任务的结果,但是正在执行的子任务之间没有明显的关联,而你又不想做无谓的等待时,可以用这个API,提升操作的效率。

其实你可以用线程池加一个Future的队列也可以做到,就是需要不停的遍历。

问题

扩展

参考文献

相关文章

  • 8-CompletionService

    概述 引入 我们在上一节讲invokeAny()时讲到了一个新的接口CompletionService,我们本节对...

网友评论

      本文标题:8-CompletionService

      本文链接:https://www.haomeiwen.com/subject/msgtfhtx.html