10-Callable与Future的应用

CompletionService与ExecutorService类似都可以用来执行线程池的任务

范例:

package cn.itcast.demo.thread;

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 CallableAndFuture {
	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		Future<String> future = threadPool.submit(new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(2000);
				return "Hello";
			}
		});
		
		try {
			System.out.println("等待结果...");
			System.out.println("拿到结果: " + future.get());
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}
}

打印结果:

等待结果...
拿到结果: Hello

 

范例:获取线程的执行结果

package cn.itcast.demo.thread;

import java.util.Random;
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;

public class CallableAndFuture {
	public static void main(String[] args) {
		// 产生线程池,这个线程池中有固定的10个线程
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		// 处理完成后的结果
		CompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);
		for (int i=1; i<=10; i++) {
			final int seq = i;
			completionService.submit(new Callable<String>() {
				@Override
				public String call() throws Exception {
					Thread.sleep(new Random().nextInt(5000));
					return "sequence of thread: " + seq;
				}
			});
		}
		// 获取返回结果
		for (int i=0; i<10; i++) {
			try {
				System.out.println(completionService.take().get());
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}
		}
	}
}

打印结果:

sequence of thread: 3
sequence of thread: 6
sequence of thread: 5
sequence of thread: 4
sequence of thread: 8
sequence of thread: 10
sequence of thread: 7
sequence of thread: 1
sequence of thread: 9
sequence of thread: 2

 

posted @ 2017-08-17 17:21  半生戎马,共话桑麻、  阅读(120)  评论(0)    收藏  举报
levels of contents