我用例:如何創建一個ThreadPoolExecutor,根據需要創建線程並在適用時將其過期?
- 設置最小大小「N」對於這意味着「N」螺紋總是執行人啓動後的可用線程池。
- 設置線程池的最大大小'M'。
- 當所有'M'線程忙時,傳入任務應該排隊。
- 基於空閒狀態超時期滿(M-N)線程。
我相信HttpClient後面的池管理器可能有類似的設置。我試圖用ThreadPoolExecutor來實現它,但無法找到一種方法。可能嗎?
這是一個測試的例子。
public class ExecutorExample {
public static void main(String[] args) throws InterruptedException {
int minPoolSize = 2;
int maxPoolSize = 10;
int ttlMillis = 100;
ThreadPoolExecutor startupExecutor = new ThreadPoolExecutor(minPoolSize,
maxPoolSize, // surprisingly this is not obeyed.
ttlMillis,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + ":" + startupExecutor.getCorePoolSize());
startupExecutor.execute(new MyRunnable(i));
}
for (int i = 0; i < 20; i++) {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + ":" + startupExecutor.getCorePoolSize());
}
}
}
class MyRunnable implements Runnable {
int n;
public MyRunnable(int n) {
this.n = n;
}
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + ":" + n);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
'ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue)'是否符合您的需求? –
@RomanPuchkovskiy你想到哪個隊列對象?我會測試。 – phani
這是一個奇怪的要求......爲什麼在傳入任務排隊之前,需要將線程數從N增加到M *? –