繁体   English   中英

了解ThreadPoolExecutor内部工作

[英]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的工作方式正确:

  1. 如果NumberOfThreadRunning <CoreNumberOfThreads,则ThreadPoolExecutor创建一个新线程来完成任务。
  2. 如果NumberOfThreadRunning> CoreNumberOfThreads然后将该任务在BlockingQueue中排队,但是如果队列已满,则仅在NumberOfThread <MaxNumberOfThreads时创建一个新线程。
  3. 任务完成后,运行该任务的线程可用于其他任务。

根据第三点。 我应该能够使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM