[英]Understanding ThreadPoolExecutor internal working
我有以下代碼:
public class ExecFramework implements Runnable {
int i;
public ExecFramework() {
}
public ExecFramework(int i) {
this.i = i;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " " + i);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ExecutorService pool=new ThreadPoolExecutor(2, 10, 5000,TimeUnit.SECONDS, new ArrayBlockingQueue(2));
for (int i = 0; i < 20; i++) {
Runnable obj=new ExecFramework(i);
pool.execute(obj);
}
pool.shutdown();
while(pool.isTerminated()){
System.out.println("ExecutorService is terminated");
}
}
}
我是否了解ThreadPoolExecutor的工作方式正確:
- 如果NumberOfThreadRunning <CoreNumberOfThreads,則ThreadPoolExecutor創建一個新線程來完成任務。
- 如果NumberOfThreadRunning> CoreNumberOfThreads然后將該任務在BlockingQueue中排隊,但是如果隊列已滿,則僅在NumberOfThread <MaxNumberOfThreads時創建一個新線程。
- 任務完成后,運行該任務的線程可用於其他任務。
根據第三點。 我應該能夠使用ThreadPoolExecutor執行20個任務。
為什么上面的代碼輸出是?
pool-1-thread-5 6 pool-1-thread-4 5 pool-1-thread-3 4 pool-1-thread-1 0 pool-1-thread-2 1 pool-1-thread-6 7 pool-1-thread-7 8 pool-1-thread-8 9 pool-1-thread-9 10 pool-1-thread-10 11 Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task executionFramework.ExecFramework@232204a1 rejected from java.util.concurrent.ThreadPoolExecutor@4aa298b7[Running, pool size = 10, active threads = 10, queued tasks = 2, completed tasks = 0] at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063) at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830) at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379) at executionFramework.ExecFramework.main(ExecFramework.java:88) pool-1-thread-8 2 pool-1-thread-6 3
該文檔說: https : //docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html
在“ 拒絕的任務”部分中。
在您的情況下,我會猜這:
當執行器對最大線程和工作隊列容量都使用有限范圍時,並且飽和
發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.