【问题标题】:Understanding ThreadPoolExecutor internal working了解 ThreadPoolExecutor 内部工作
【发布时间】:2018-03-21 22:50:41
【问题描述】:

我有以下代码:

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
  2. 如果 NumberOfThreadRunning > CoreNumberOfThreads 然后将此任务排队在 BlockingQueue 但如果队列已满则仅在以下情况下创建一个新线程 NumberOfThread
  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

【问题讨论】:

    标签: java threadpoolexecutor


    【解决方案1】:

    文档说:https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html

    拒绝的任务部分。

    在你的情况下,我猜这个:

    当 Executor 对最大线程和工作队列容量都使用有限界限,并且已经饱和时

    发生了。

    【讨论】:

    • 我对 ThreadPoolExecutor 的理解正确吗?我在问题中给出的 3 点
    • 每当我们在 ThreadPoolExecutor 上调用 execute 时,它​​总是会在 ThreadPoolExecutor 中创建一个新线程吗?
    • 没有 ThreadPoll 根据需要创建线程,直到定义的最大值。当你给一个工作队列时,就像你做的那样,并且这个队列已经饱和,没有可用的线程,就会发生这种情况。尽量不要提供这个工作队列或者只是让它更大。工作队列保存可运行文件,直到它们被发布到执行程序。在您的情况下,执行程序中的线程很忙,并且保存要转发到池的可运行对象的队列也已满
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    相关资源
    最近更新 更多