ExecutorService之invokeAll和invokeAny的使用場景

先看看ExecutorService中的這幾個方法

public interface ExecutorService extends Executor {  

    //不再接受新任務(wù),待所有任務(wù)執(zhí)行完畢后關(guān)閉ExecutorService  
    void shutdown();  

    //不再接受新任務(wù),直接關(guān)閉ExecutorService,返回沒有執(zhí)行的任務(wù)列表  
    List<Runnable> shutdownNow();  

    //判斷ExecutorService是否關(guān)閉  
    boolean isShutdown();  

    //判斷ExecutorService是否終止  
    boolean isTerminated();  

    //等待ExecutorService到達(dá)終止?fàn)顟B(tài)  
    boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;  
    <T> Future<T> submit(Callable<T> task);  

    //當(dāng)task執(zhí)行成功的時候future.get()返回result  
    <T> Future<T> submit(Runnable task, T result);  

    //當(dāng)task執(zhí)行成功的時候future.get()返回null  
    Future<?> submit(Runnable task);  

    //批量提交任務(wù)并獲得他們的future,Task列表與Future列表一一對應(yīng)  
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)  
        throws InterruptedException;  

    //批量提交任務(wù)并獲得他們的future,并限定處理所有任務(wù)的時間  
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,  
    long timeout, TimeUnit unit) throws InterruptedException;  

    //批量提交任務(wù)并獲得一個已經(jīng)成功執(zhí)行的任務(wù)的結(jié)果  
    <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException;  
  
    <T> T invokeAny(Collection<? extends Callable<T>> tasks,  
                    long timeout, TimeUnit unit)  
        throws InterruptedException, ExecutionException, TimeoutException;  
}  

應(yīng)用場景

  1. invokeAny

需求描述:海量數(shù)據(jù)文件系統(tǒng),我們需要找出其中某個資源(可以確定的是,該文件系統(tǒng)的資源都是唯一的)

我們可能啟動多個線程去各自負(fù)責(zé)自己的區(qū)域,比如線程A負(fù)責(zé)Area_A,線程B負(fù)責(zé)Area_B,這樣可以大規(guī)模的提升速度。但是我們希望只要其中一個線程找到符合要求的數(shù)據(jù)時 我們就立即返回,而不用還讓其他線程繼續(xù)執(zhí)行下去,這樣可以節(jié)省CPU使用率。而invokeAny就可以很好的解決這個問題,只要其中一個線程執(zhí)行完了,就會立即返回,其他線程就會退出,不在占用cpu資源。

  1. invokeAll

需求描述:海量數(shù)據(jù)文件系統(tǒng)的搜索功能,但和上面的不同,里面存在多個相似的資源,需要全部查出來。

  1. invokeAll超時方法


    image.png

    在指定的時間范圍內(nèi),如果沒有執(zhí)行完,則取消沒有執(zhí)行完的任務(wù)。

相關(guān)測試DEMO請參考:https://github.com/jerrik123/ExecutorService_invokeAll_Any

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容