Java 杂谈写作与程序程序员

学习Java基础知识,打通面试关~十六自定义线程池

2018-07-12  本文已影响159人  胖琪的升级之路

在上篇文章中我们了解到了Java是怎么来建立自带的线程池的,虽然Java中提供了多种线程池,但是我们还是在某些场景下需要实现自己的线程池操作。

新建立线程

在阿里的指导手册里面,也是建议自己使用该方式进行创建线程池。


新建线程池
 ExecutorService   service =   ExecutorService   service = new ThreadPoolExecutor(1, 10, 0L,
                TimeUnit.MINUTES, new LinkedBlockingDeque<>(), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return null;
            }
        }, new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

            }
        });
 new ThreadPoolExecutor.AbortPolicy();
 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());
        }
    }
  1. DiscardPolicy : 是AbortPolicy的slient版本,线程池队列满了,会丢掉任务,并且不会又异常抛出。
 public static class DiscardPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardPolicy}.
         */
        public DiscardPolicy() { }

        /**
         * Does nothing, which has the effect of discarding task r.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        }
    }
  1. DiscardOldestPolicy : 丢弃最老的任务。队列满了会把最早进入的任务进行删除,在尝试进入队列。
 public static class DiscardOldestPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardOldestPolicy} for the given executor.
         */
        public DiscardOldestPolicy() { }

        /**
         * Obtains and ignores the next task that the executor
         * would otherwise execute, if one is immediately available,
         * and then retries execution of task r, unless the executor
         * is shut down, in which case task r is instead discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                e.getQueue().poll(); //从头部移除。
                e.execute(r);
            }
        }
    }
  1. CallerRunsPolicy:当添加线程池失败的时候,主线程会自己去执行该任务,不会等待线程池中的线程去执行。
 public static class CallerRunsPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code CallerRunsPolicy}.
         */
        public CallerRunsPolicy() { }

        /**
         * Executes task r in the caller's thread, unless the executor
         * has been shut down, in which case the task is discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                r.run();
            }
        }
    }
  1. 自定义线程池:写实现类实现RejectedExecutionHandler 。来实现自己的拒绝策略
public class RejectHander implements RejectedExecutionHandler{
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
         //写自己的业务拒绝策略 
    }
}

整个线程池执行流程 。

  1. 任务提交 小于corePoolSize就分配线程执行。
  2. 大于corePoolSize 提交到等待队列
  3. 成功那么就等待执行。
  4. 失败提交线程池进行判断是否大于maximumPoolSize ,提交失败那么拒绝执行。
  5. 小于maximumPoolSize ,那么就分配线程进行任务的执行。


    执行流程
上一篇 下一篇

猜你喜欢

热点阅读