// 創建一個線程
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來封裝。