线程池-阻塞队列:默认值

1,104 阅读1分钟

比如,固定线程池。

代码

private static ExecutorService executorService = Executors.newFixedThreadPool(3); 

固定线程池,只有一个参数,但是其他的三个参数都是有默认值的:
1.max //和min一样
2.阻塞队列 //链表阻塞队列,且大小是无限大,具体是int的最大值,基本上相当于是无限大
3.拒绝参数 //丢弃

max

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads //和min一样,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>() //阻塞队列);
    }

阻塞队列

**
     * Creates a {@code LinkedBlockingQueue} with a capacity of
     * {@link Integer#MAX_VALUE}.
     */
    public LinkedBlockingQueue() {
        this(Integer.MAX_VALUE); //默认是最大值
    }

拒绝参数

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler //默认拒绝参数);
    }
/**
     * The default rejected execution handler
     */
    private static final RejectedExecutionHandler defaultHandler =
        new AbortPolicy();
/**
     * A handler for rejected tasks that throws a
     * {@code RejectedExecutionException}.
     */
    public static class AbortPolicy implements RejectedExecutionHandler {
        /**
         * Creates an {@code AbortPolicy}.
         */
        public AbortPolicy() { }

        /**
         * Always throws RejectedExecutionException.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         * @throws RejectedExecutionException always.
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString()); //被丢弃。具体处理就是向上抛异常。
        }
    }

应用场景

支付系统的转账。

参考

官方api文档