首页 > 其他 > 详细

Java多线程研究(七)Callable与Future的应用

时间:2014-01-20 22:55:05      阅读:321      评论:0      收藏:0      [点我收藏+]

ExecutorService.submit()会返回一个future.

blic static void main(String[] args) {
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		Future future = 
		threadPool.submit(
				new Callable<String>() {
					public String call() throws Exception{
						Thread.sleep(2000);
						return "hello";
						};
					}
				);
		
		System.out.println("等待结果");
		try {
			System.out.println("等待结果"+future.get());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

运行结果:

等待结果
等待结果hello

而如果使用CompletionService.submit方法,会在多个任务运行时,按照完成的先后顺序依次返回,看代码:

ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
		CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);
		for(int i=0;i<10;++i){
			final int seq = i;
			
			completionService.submit(new Callable<Integer>() {
	
				@Override
				public Integer call() throws Exception {
					Thread.sleep(new Random().nextInt(5000));
					return seq;
				}
				
			});
			}
		for(int i=0;i<10;++i){
			try {
				System.out.println(completionService.take().get());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

运行结果:

2
8
0
1
5
3
6
7
4
9

Java多线程研究(七)Callable与Future的应用

原文:http://blog.csdn.net/howlaa/article/details/18459925

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!