读ExecutorCompletionService源码_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 读ExecutorCompletionService源码

读ExecutorCompletionService源码

 2017/9/23 12:38:28  红领巾丶  程序员俱乐部  我要评论(0)
  • 摘要://一个用来管理已完成任务的service,内部封装了一个队列。//它是CompletionService的一个实现publicclassExecutorCompletionService<V>implementsCompletionService<V>//先看构造函数publicExecutorCompletionService(Executorexecutor){if(executor==null)thrownewNullPointerException()
  • 标签:Service 源码
class="java" name="code">
//一个用来管理已完成任务的service,内部封装了一个队列。
//它是CompletionService的一个实现
public class ExecutorCompletionService<V> implements CompletionService<V>
//先看构造函数


public ExecutorCompletionService(Executor executor) {
        if (executor == null)
            throw new NullPointerException();
        this.executor = executor;
        this.aes = (executor instanceof AbstractExecutorService) ?
            (AbstractExecutorService) executor : null;
        this.completionQueue = new LinkedBlockingQueue<Future<V>>();
    }

public ExecutorCompletionService(Executor executor,
                                     BlockingQueue<Future<V>> completionQueue) {
        if (executor == null || completionQueue == null)
            throw new NullPointerException();
        this.executor = executor;
        this.aes = (executor instanceof AbstractExecutorService) ?
            (AbstractExecutorService) executor : null;
        this.completionQueue = completionQueue;
    }

//提交任务返回Future
public Future<V> submit(Callable<V> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<V> f = newTaskFor(task);
        executor.execute(new QueueingFuture(f));
        return f;
    }

private RunnableFuture<V> newTaskFor(Callable<V> task) {
        if (aes == null)
            return new FutureTask<V>(task);
        else
            return aes.newTaskFor(task);
    }

private class QueueingFuture extends FutureTask<Void> {
        QueueingFuture(RunnableFuture<V> task) {
            super(task, null);
            this.task = task;
        }
	//这句是关键,当完成任务的时候加入到队列中
        protected void done() { completionQueue.add(task); }
        private final Future<V> task;
    }

//提交Runnable任务返回Future
public Future<V> submit(Runnable task, V result) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<V> f = newTaskFor(task, result);
        executor.execute(new QueueingFuture(f));
        return f;
    }

 public Future<V> take() throws InterruptedException {
        return completionQueue.take();
    }

    public Future<V> poll() {
        return completionQueue.poll();
    }

    public Future<V> poll(long timeout, TimeUnit unit)
            throws InterruptedException {
        return completionQueue.poll(timeout, unit);
    }

上一篇: Google资助的研究称Chrome最善于抵御攻击 下一篇: 没有下一篇了!
发表评论
用户名: 匿名