I am having following code:
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");
}
}
}
Is my knowledge for the way ThreadPoolExecutor works correct:
- If NumberOfThreadRunning < CoreNumberOfThreads then ThreadPoolExecutor creates a new thread to complete the task.
- If NumberOfThreadRunning > CoreNumberOfThreads then queue this task in BlockingQueue but if queue is full then create a new Thread only if NumberOfThread < MaxNumberOfThreads.
- Once the task is completed thread running that task is available for other task.
According to 3rd point. I should be able to execute 20 tasks using ThreadPoolExecutor.
Why Output of above code is?
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
The documentation says it: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html
In section Rejected tasks .
In your case i would guess this :
when the Executor uses finite bounds for both maximum threads and work queue capacity, and is saturated
happens.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.