[英]How does Keep-alive work with ThreadPoolExecutor?
繼續我發布的問題 ,我正在嘗試在我的代碼庫中使用ThreadPoolExecutor 。 即使在多次嘗試從Java API doc中理解之后,我也無法清楚地理解keepAliveTime
參數在構造函數中傳遞的功能/目的。 希望有人能用一些好的工作實例來解釋我。
摘自Java doc:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue)
keepAliveTime
- 當線程數大於核心時,這是多余空閑線程在終止之前等待新任務的最長時間。
假設您的核心大小為5,最大大小為15.由於某種原因,您的池會變忙,並使用所有15個可用線程。 最終你沒有工作要做 - 所以你的一些線程在完成最后的任務時就會空閑。 因此,其中10個線程被允許死亡。
但是,為了避免它們被快速殺死,您可以指定保持活動時間。 因此,如果您將keepAliveTime
值指定為1並將TimeUnit.MINUTE
指定為unit
值,則每個線程在完成執行任務后等待一分鍾,以查看是否還有更多工作要做。 如果它還沒有得到任何更多的工作,它將自己完成,直到池中只有5個線程 - 池的“核心”。
以下是Javadoc的更多描述:
<dt>Keep-alive times</dt>
*
* <dd>If the pool currently has more than corePoolSize threads,
* excess threads will be terminated if they have been idle for more
* than the keepAliveTime (see {@link
* ThreadPoolExecutor#getKeepAliveTime}). This provides a means of
* reducing resource consumption when the pool is not being actively
* used. If the pool becomes more active later, new threads will be
* constructed. This parameter can also be changed dynamically
* using method {@link ThreadPoolExecutor#setKeepAliveTime}. Using
* a value of <tt>Long.MAX_VALUE</tt> {@link TimeUnit#NANOSECONDS}
* effectively disables idle threads from ever terminating prior
* to shut down.
* </dd>
*
從本質上講,這只允許您控制空閑池中剩余的線程數。 如果你把它做得太小(對於你正在做的事情),你將創建太多的線程。 如果你把它做得太大,你將消耗你不需要的內存/線程。
下面是代碼示例,它演示了keepAliveTime的工作ThreadPoolExecutor的maximumPoolSize 如何工作?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.