线程池最大线程数不正确

The maximum number of threads in the thread pool is incorrect

我有一个最大线程数为3的线程池,但是只执行了一个线程,怎么回事?

public class Volatile {

    private volatile static boolean keepA = true;
    private static boolean keepB = true;

    private static ExecutorService executor = new ThreadPoolExecutor(1,
            3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>() );

    public static void main(String[] args) {
        executor.execute(() -> {
            while (keepA) {
                System.out.println("keepA running...");
            }
            System.out.println("keepA stop!!!!!!");
        });
        executor.execute(() -> {
            while (keepB) {
                System.out.println("keepB running...");
            }
            System.out.println("keepB stop!!!!!!");
        });
        executor.execute(() -> {
            keepA = false;
            keepB = false;
        });
        while (true) {

        }
    }
}

结果

keepA running...
keepA running...
keepA running...
......

ThreadPoolExecutor 的第一个参数是并行线程的初始数量 运行。您已将其设置为 1。将其更改为 3,然后重试。只有当队列已满时,此大小才应该增长,但您的队列是无限大的,永远不会满。

public ThreadPoolExecutor(int corePoolSize,
              int maximumPoolSize,
              long keepAliveTime,
              TimeUnit unit,
              BlockingQueue<Runnable> workQueue)

Creates a new ThreadPoolExecutor with the given initial parameters and default rejected execution handler.

Parameters:

  • corePoolSize - the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set

  • maximumPoolSize - the maximum number of threads to allow in the pool

  • keepAliveTime - when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.

  • unit - the time unit for the keepAliveTime argument

  • workQueue - the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.

Throws:

  • IllegalArgumentException - if one of the following holds:

    `corePoolSize < 0`
    `keepAliveTime < 0`
    `maximumPoolSize <= 0`
    `maximumPoolSize < corePoolSize` 
    
  • NullPointerException - if workQueue or threadFactory is null

非核心线程只会在队列已满时启动(并且您有一个无界队列,因此永远不会发生)。

作为per Javadoc:

Any BlockingQueue may be used to transfer and hold submitted tasks. The use of this queue interacts with pool sizing:

  • If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing.
  • If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.
  • If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected.