首页  

Java线程池ExecutorService与CompletionService     所属分类 java 浏览量 1247
并行执行任务并获取返回结果
CompletionService 执行快的先返回

ExecutorService 例子


public class FutureTest {
	
	private static ExecutorService pool = Executors.newCachedThreadPool();
	private static Random rand = new Random();
	
	public static void main(String[] args) throws Exception {
		System.out.println("FutureTest start "+new Date());	
		int num = 3;
		List<Future<Long>> futures = new ArrayList<Future<Long>>();
		Future<Long> future = null;
		long sleepTime = 500;
		for(int i=0;i<num;i++){
			sleepTime = sleepTime + rand.nextInt(1000);
			// MyCallable 模拟任务 sleep 指定时间返回 
			future = pool.submit(new MyCallable("task"+i,sleepTime));
			futures.add(future);
		}
		for(int i=0;i<num;i++){
			System.out.println(futures.get(i).get());
		}
		pool.shutdown();
	}
}



CompletionService 例子 public class CompleteServiceTest { private static ExecutorService pool = Executors.newCachedThreadPool(); private static Random rand = new Random(); public static void main(String[] args) throws Exception { System.out.println("CompleteServiceTest start "+new Date()); CompletionService<Long> cs = new ExecutorCompletionService<>(pool); int num = 3; long sleepTime = 500; for(int i=0;i<num;i++){ sleepTime = sleepTime + rand.nextInt(1000); cs.submit(new MyCallable("task"+i,sleepTime)); } for(int i=0;i<num;i++){ // 响应快的先返回 System.out.println(cs.take().get()); } System.out.println("CompleteService done "+new Date()); Utils.doSleep(1000); System.out.println("sleep done "+new Date()); pool.shutdown(); pool.awaitTermination(10, TimeUnit.SECONDS); } }
完整例子代码 https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/conc/FutureTest.java https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/conc/CompleteServiceTest.java

上一篇     下一篇
文件内容对比技巧

Maven命令行直接运行SpringBoot项目

mediumtext和text的区别

使用aql更新lua脚本

metaspace OOM 实例

规则引擎easyrules