// 创建一个线程
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(new Callable<String>() {
@Override
public String call() throws InterruptedException {
Thread.sleep(1000);
return "success";
}
});
System.out.println(future.get());
//创建十个线程
ExecutorService threadPool = Executors.newFixedThreadPool(10);
CompletionService<Integer> completionService = new ExecutorCompletionService<>(threadPool);
for (int i = 0; i < 10; i++) {
final int sq = i;
completionService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(new Random().nextInt(1000));
return sq;
}
});
}
for (int i = 0; i < 10; i++) {
System.out.println(completionService.take().get());
}
Callable 和Runable最大的区别就是Callable是有返回值的,用线程池ExecutorService创建线程的时候,不妨把这个线程池交给ExecutorCompletionService类来处理。可以将返回值用list来封装。
原文地址:http://7981774.blog.51cto.com/7971774/1621606