线程池 详解

三大方法

//Executors.newCachedThreadPool();  可伸缩的,遇强则强,遇弱则弱
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,// 最多21亿
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}

//底层的阻塞队列是LinkedBlockingQueue,它的默认请求队列长度为Integer.MAX_VALUE;
//Executors.newFixedThreadPool(int nThreads);创建一个固定的线程池的大小
public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
}
    
/底层的阻塞队列是LinkedBlockingQueue,它的默认请求队列长度为Integer.MAX_VALUE;    
//Executors.newSingleThreadExecutor();   单个线程
public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
}

七大参数

//ThreadPoolExecutor的构造方法《  七大参数 》

 /**
     * 
     * @param corePoolSize  核心线程数
     * @param maximumPoolSize  最大线程数
     * @param keepAliveTime		线程保持alive时间,超时了没有人调用就会释放
     * @param unit				keepAliveTime超时单位
     * @param workQueue			阻塞队列
     * @param threadFactory		线程工厂,创建线程的,一般不用动
     * @param handler			拒绝策略
     */
 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

image-20220305184120549

四个拒绝策略

/**
* new ThreadPoolExecutor.AbortPolicy() // 		银行满了,还有人进来,不处理这个人的,抛出异常
* new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里!
* new ThreadPoolExecutor.DiscardPolicy() //		队列满了,丢掉任务,不会抛出异常!
* new ThreadPoolExecutor.DiscardOldestPolicy() //队列满了,尝试去和最早的竞争,也不会抛出异常!
*/  


/**
     * A handler for rejected tasks that runs the rejected task
     * directly in the calling thread of the {@code execute} method,
     * unless the executor has been shut down, in which case the task
     * is discarded.
     被拒绝任务的处理程序,直接在执行方法的调用线程中运行被拒绝的任务,除非执行程序已关闭,在这种情况下,任务将被丢弃。
     */
    public static class CallerRunsPolicy implements RejectedExecutionHandler {
      
        public CallerRunsPolicy() { }

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                r.run();
            }
        }
    }

    /**
     * A handler for rejected tasks that throws a
     * {@code RejectedExecutionException}.
     抛出 RejectedExecutionException 的被拒绝任务的处理程序。
     */
    public static class AbortPolicy implements RejectedExecutionHandler {
        /**
         * Creates an {@code AbortPolicy}.
         */
        public AbortPolicy() { }

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
    }

    /**
     * A handler for rejected tasks that silently discards the
     * rejected task.
     被拒绝任务的处理程序,它默默地丢弃被拒绝的任务。
     */
    public static class DiscardPolicy implements RejectedExecutionHandler {
  
        public DiscardPolicy() { }
     
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        }
    }

    /**
     * A handler for rejected tasks that discards the oldest unhandled
     * request and then retries {@code execute}, unless the executor
     * is shut down, in which case the task is discarded.
     拒绝任务的处理程序,丢弃最旧的未处理请求,然后重试执行,除非执行程序被关闭,在这种情况下任务被丢弃。
     */
    public static class DiscardOldestPolicy implements RejectedExecutionHandler {
  
        public DiscardOldestPolicy() { }

  
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                e.getQueue().poll();
                e.execute(r);
            }
        }
    }
posted @ 2022-03-13 16:51  timberwang  阅读(37)  评论(0)    收藏  举报