Java CompletionService 理解__java

來源:互聯網
上載者:User

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 + "]";
}


}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.