CompletionService
大致思路
CompletionService将Executor(线程池)和BlockingQueue(堵塞队列)结合在一起,同一时候使用Callable作为任务的基本单元,整个过程就是生产者不断把Callable任务放入堵塞队列,Executor作为消费者不断把任务取出来运行,并返回结果;
优势:
-
堵塞队列防止了内存中排队等待的任务过多,造成内存溢出(毕竟一般生产者速度比较快,消费者还是比较慢)
-
CompletionService能够实现,哪个任务先运行完毕就返回,而不是按顺序返回,这样能够极大的提升效率;
ExecutorService
大致思路
1.ExecutorService的invokeAll方法也能批量运行任务,并批量返回结果
2.当所有任务都执行完毕或者调用线程被中断又或者超过指定时限后,invokeAll将返回。
3.invokeAll可以设置超时时间。超过时限后,任何尚未完成的任务都会被取消。
4.作为invokeAll的返回值,每个任务要么正常地完成,要么被取消。
5.任务被取消后调用get会抛出异常
缺点:
-
必须等待全部的任务运行完毕后统一返回。
-
内存持有的时间长,响应性也有一定的影响
代码
CompletionService代码
package com.zhy.concurrency.completionService;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
/**
* 将Executor和BlockingQueue功能融合在一起,能够将Callable的任务提交给它来运行, 然后使用take()方法获得已经完毕的结果
*
* @author zhy
*
*/
public class CompletionServiceDemo{
public static void main(String[] args) throws InterruptedException,
ExecutionException{
/**
* 内部维护11个线程的线程池
*/
ExecutorService exec = Executors.newFixedThreadPool(11);
/**
* 容量为10的堵塞队列
*/
final BlockingQueue<Future<Integer>> queue = new LinkedBlockingDeque<Future<Integer>>(
10);
//实例化CompletionService
final CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(
exec, queue);
/**
* 模拟瞬间产生10个任务,且每一个任务运行时间不一致
*/
for (int i = 0; i < 10; i++){
completionService.submit(new Callable<Integer>()
{
@Override
public Integer call() throws Exception
{
int ran = new Random().nextInt(1000);
Thread.sleep(ran);
System.out.println(Thread.currentThread().getName()
+ " 歇息了 " + ran);
return ran;
}
});
}
/**
* 马上输出结果
*/
for (int i = 0; i < 10; i++){
try
{
//谁最先运行完毕,直接返回
Future<Integer> f = completionService.take();
System.out.println(f.get());
} catch (InterruptedException e){
e.printStackTrace();
} catch (ExecutionException e)
{
e.printStackTrace();
}
}
exec.shutdown();
}
}
CompletionService结果
最先运行完毕的直接返回,并不须要按任务提交的顺序运行
pool-1-thread-4 歇息了 52
52
pool-1-thread-1 歇息了 59
59
pool-1-thread-10 歇息了 215
215
pool-1-thread-9 歇息了 352
352
pool-1-thread-5 歇息了 389
389
pool-1-thread-3 歇息了 589
589
pool-1-thread-2 歇息了 794
794
pool-1-thread-7 歇息了 805
805
pool-1-thread-6 歇息了 909
909
pool-1-thread-8 歇息了 987
987
ExecutorService代码
package com.zhy.concurrency.executors;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestInvokeAll{
public static void main(String[] args) throws InterruptedException,
ExecutionException{
ExecutorService exec = Executors.newFixedThreadPool(10);
List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
Callable<Integer> task = null;
for (int i = 0; i < 10; i++){
task = new Callable<Integer>()
{
@Override
public Integer call() throws Exception
{
int ran = new Random().nextInt(1000);
Thread.sleep(ran);
System.out.println(Thread.currentThread().getName()+" 歇息了 " + ran );
return ran;
}
};
tasks.add(task);
}
long s = System.currentTimeMillis();
List<Future<Integer>> results = exec.invokeAll(tasks);
System.out.println("运行任务消耗了 :" + (System.currentTimeMillis() - s) +"毫秒");
for (int i = 0; i < results.size(); i++){
try{
System.out.println(results.get(i).get());
} catch (Exception e){
e.printStackTrace();
}
}
exec.shutdown();
}
}
ExecutorService结果
invokeAll返回是等待全部线程运行完毕的
pool-1-thread-10 歇息了 1
pool-1-thread-5 歇息了 59
pool-1-thread-6 歇息了 128
pool-1-thread-1 歇息了 146
pool-1-thread-3 歇息了 158
pool-1-thread-7 歇息了 387
pool-1-thread-9 歇息了 486
pool-1-thread-8 歇息了 606
pool-1-thread-4 歇息了 707
pool-1-thread-2 歇息了 817
运行任务消耗了 :819毫秒
146
817
158
707
59
128
387
606
486
1