簡體   English   中英

執行器服務的所有線程都在處理任務時是否可以等待主線程

[英]Is it possible to wait the main thread while all the threads of executor service are processing tasks

我有一個將數百萬數據插入后端並且當前使用執行器框架來加載它的場景。 我將用更簡單的術語解釋我的問題。

在下面的情況下,我有 10 個可運行的線程和三個線程來執行相同的操作。 考慮我的可運行對象正在執行插入操作,完成任務需要時間。 當我檢查時,據了解,如果所有線程都忙,其他任務將 go 到隊列中,一旦線程完成任務,它將從池中獲取任務並完成它。

所以在這種情況下,SampleRunnable 4 到 10 的 object 將被創建,這將在池中。

問題:由於我需要加載數百萬個任務,我無法加載隊列中的所有記錄,這可能導致 memory 問題。 所以我的問題是,不是將所有任務都放在隊列中,是否可以讓主線程等待,直到任何一個執行器工作線程可用。

以下方法我嘗試解決而不是排隊這么多任務:

方法 1:使用 Array Blocking Queue 作為 executor 並將大小設為 5(例如)所以在這種情況下,當第 9 個任務到來時,這將拋出 RejectedExecutionException 並在 catch 子句中,休眠 1 分鍾並遞歸嘗試同樣。當線程可用時,這將在任何重試時被拾取。

方法2:使用關閉並等待終止。 即,如果任務計數為 5,我將關閉並等待終止。 在 await Termination 'if' 塊(executor.awaitTermination(60000,TimeUnit.SECONDS))中,我再次實例化線程池。


public class SampleMain {

public static void main(String[] args) {

ExecutorService executor = Executors.newFixedThreadPool(3);

for (int i=0;i<10;i++){ 
   executorService.execute(new SampleRunnable(i));
}

executor.shutdown();
}

聽起來問題是,你想限制主線程,這樣它就不會領先於工人。 如果是這種情況,那么考慮顯式構造一個ThreadPoolExecutor實例而不是調用Executors.newFixedThreadPool()

class 有幾個不同的構造函數,其中大多數允許您提供自己的阻塞隊列。 如果創建一個大小有限的ArrayBlockingQueue ,那么每次隊列滿時,主線程都會自動阻塞,直到有一個工作線程通過另一個任務騰出空間。

final int work_queue_size = 30;
BlockingQueue work_queue = new ArrayBlockingQueue(work_queue_size);
ExecutorService executor = new ThreadPoolExecutor(..., work_queue);

for (int i=0;i<10;i++){ 
    executorService.execute(new SampleRunnable(i));
}
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM