簡體   English   中英

如何更改 ScheduledExecutorService 中的線程池大小?

[英]How to change thread pool size in ScheduledExecutorService?

我需要帶有動態線程池的 ScheduledExecutorService。 我想動態更改線程池大小。 我怎樣才能做到這一點?

class ExecutorTask {
    private ScheduledExecutorService service;

    public void add(Task task) {
        // I need thread pool size == count added tasks.
        service.scheduleAtFixedRate(this::start, 0, 10, TimeUnit.SECONDS);
    }
}

也許你可以建議我另一個線程池?

您可以使用ScheduledThreadPoolExecutor輕松做到這一點。

    //Init executor
    int initialPoolSize = 5;
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(initialPoolSize);

    //[...] do something

    //Change max size
    int newPoolSize = 10;
    executor.setCorePoolSize(newPoolSize);

請注意,繼承的方法setMaximumPoolSize(int) 對 ScheduledThreadPoolExecutor 沒有影響 要更改池大小,您需要更改 corePoolSize:

雖然這個類繼承自 ThreadPoolExecutor,但一些繼承的調優方法對它沒有用。 特別是,因為它充當使用 corePoolSize 線程和無界隊列的固定大小的池,所以對 maximumPoolSize 的調整沒有任何有用的效果。 此外,將 corePoolSize 設置為零或使用 allowCoreThreadTimeOut 幾乎從來都不是一個好主意,因為一旦它們有資格運行,這可能會使池沒有線程來處理任務。

也許這就是您在 Executors Util 類中尋找的內容:

ExecutorService executorService = Executors.newScheduledThreadPool(5)

你可以使用setCorePoolSize(int)方法。

同樣使用Executors.newCachedThreadPool您負責為ThreadPoolExecutor創建線程池大小。

如果需要執行新任務, ThreadPoolExecutor創建新線程,並使用Executors.newCachedThreadPool()重用現有線程

暫無
暫無

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

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