CompletionService是一個抽象的java泛型介面,它被ExecutorCompletionService泛型類實現,具體功能是將生產的任務和生產任務產生的結果分離。生產者通過submit提交任務,消費生產結構通過take擷取任務放回的結果,然後做其他的處理。CompletionService 一般用於需要非同步作業的地方,比如網路請求,檔案io等耗時的操作中。ExecutorCompletionService 維護一個提交任務的Future BlockingQueue。ExecutorCompletionService 將Executor(線程池)和BlockingQueue(阻塞隊列)結合在一起,同時使用Callable作為任務的基本單元,整個過程就是生產者不斷把Callable任務放入阻塞對了,Executor作為消費者不斷把任務取出來執行,並返回結果;下面通過一個案例來示範一下它們的使用:
public class MyCompletionService {
public static void main(String[] args) throws InterruptedException,
ExecutionException {
ExecutorService exec = Executors.newFixedThreadPool(5);
CompletionService<MyObject> serv = new ExecutorCompletionService<MyObject>(
exec);
for (int index = 0; index < 5; index++) {
final int id = index;
/** 任務執行單元,任務執行返回一個結構, **/
Callable<MyObject> downImg = new Callable<MyObject>() {
public MyObject call() throws Exception {
//類比執行逾時任務
Thread.sleep(1000);
return new MyObject(id, "妞妞" + id);
}
};
serv.submit(downImg);
}
/** 從ExecutorCompletionService的隊列中擷取一個已經完成的Future,然後從Future裡擷取結構 **/
for (int index = 0; index < 5; index++) {
//如果隊列有結果返回,就取出來處理,如果沒有就等待
Future<MyObject> task = serv.take();
MyObject mMyObject = task.get();
System.out.println("MyObject= " + mMyObject.toString());
}
System.out.println("End");
// 關閉線程池
exec.shutdown();
}
}
class MyObject {
private int id;
private String name;
public MyObject(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "MyObject [id=" + id + ", name=" + name + "]";
}
}