深入學習理解(3):java:CompletionService解決ExecutorService的submit方法的缺點
阿新 • • 發佈:2019-02-12
在ExecutorService的submit方法中可以獲取返回值,通過Future的get方法,但是這個Future類存在缺陷,Future介面呼叫get()方法取得處理後的返回結果時具有阻塞性,也就是說呼叫Future的get方法時,任務沒有執行完成,則get方法要一直阻塞等到任務完成為止。
這樣大大的影響了系統的效能,這就是Future的最大缺點。為此,java1.5以後提供了CompletionServlice來解決這個問題。
CompletionService
介面CompletionService的功能是非同步的方式,一邊生產任務,一邊處理完成的任務結果,這樣可以將執行的任務與處理任務隔離開來進行處理,使用submit執行任務,使用塔克獲取已完成的任務,並按照這些任務的完成的時間順序來處理他們的結果。
如圖這個是CompletionService的核心方法
其有構造器如下;
CompletionService<T> completionService=new ExecutorCompletionService<T>(executorService);
可以發現,需要傳入一個executor,
下面demo來解釋CompletionService解決Future的缺點。
首先建立一個類
package com.completion; import java.util.concurrent.Callable; public class MyCallable implements Callable<String>{ private String name; private long sleep; public MyCallable(String name,long sleep) { super(); this.name=name; this.sleep=sleep; } @Override public String call() throws Exception { Thread.sleep(sleep); return "call()---->"+name; } }
測試方法
package com.completion; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.annotation.processing.Completion; public class Test { public static void main(String[] args) throws InterruptedException, ExecutionException { //模擬不同的耗時 MyCallable callable=new MyCallable("小double", 1000); MyCallable callable1=new MyCallable("大double", 4000); MyCallable callable2=new MyCallable("中double", 3000); List<Callable<String>>list=new ArrayList<>(); list.add(callable); list.add(callable1); list.add(callable2); ExecutorService executorService=Executors.newCachedThreadPool(); CompletionService<String>completionService=new ExecutorCompletionService<>(executorService); for (Callable<String>ca:list) { completionService.submit(ca); } for (Callable<String>ca:list) { System.out.println("-------------"); System.err.println(completionService.take().get()); } } }
執行效果
如此一來,,,,哈哈!Android的mvp你懂得!!!!