读ExecutorCompletionService源码
//一个用来管理已完成任务的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); }
相关推荐
Dullonjiang 2020-07-05
adayan0 2020-05-19
yanqianglifei 2020-03-03
Oeljeklaus 2020-02-18
Dullonjiang 2020-01-23
Notzuonotdied 2020-01-21
YarnSup 2020-01-10
hooopo 2014-07-12
zhixingheyitian 2019-12-06
yanqianglifei 2019-10-23
weeniebear 2015-10-16
chenchuanwen 2015-07-28
finalcola 2015-07-25
农村外出务工男 2015-05-28
lzzyok 2019-06-29
purpen 2013-01-31
chenjieit 2019-06-28