CompletionService的作用是將線程池中所有線程的執行結果future放入blockQueen隊列,take可以取出結果。
應用場景例子:對於在執行某種業務邏輯之前,需要執行1,2,3,4等步驟,這些步驟校驗完成,才能正常執行業務邏輯,而且這些步驟之前沒有關聯性,就可以應用CompletionService。
優點:放入線程池中,提高了處理性能,更快的處理返回結果
/**
* Created by liuzhilei on 2017/3/24.
*
* CompletionService是將線程池中所有線程的執行結果future放入blockQueen隊列,take可以取出結果
* 應用:對於多重驗證,如果互相之間沒有關聯,可以應用CompletionService,利用線程池,提高性能,更快的處理返回結果
*/
public class CompletionServiceDemo {
public static class Task implements Callable<Integer> {
private int i;
public Task(int i) {
this.i = i;
}
@Override
public Integer call() throws Exception {
Thread.sleep(new Random().nextInt(5000));
System.out.println("ThreadName : " + Thread.currentThread().getName());
return i;
}
}
public void run() {
ExecutorService executorService = Executors.newFixedThreadPool(10);
CompletionService completionService = new ExecutorCompletionService(executorService);
try {
for (int i = 0; i < 10; i++) {
executorService.submit(new CompletionServiceDemo.Task(i));
}
for (int i = 0; i < 10; i++) {
//take等待下一個結果並且返回future對象
//poll不等待,有結果就返回future對象,沒有就返回null
//completionService.poll();
System.out.println(completionService.poll().get());
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CompletionServiceDemo completionServiceDemo = new CompletionServiceDemo();
completionServiceDemo.run();
}
}