线程池简介

来源:互联网 发布:蓝鸥学校java培训 编辑:程序博客网 时间:2024/06/05 10:15

为了避免频繁地创建和销毁线程,使用线程池来进行复用。

这里写图片描述

这里写图片描述

  • newFixedThreadPool(int nThreads): 固定线程数的线程池

  • newSingleThreadExecutor(): 可复用的单线程执行器

  • newCachedThreadPool(): 根据情况来创建线程,如果线程有空闲则复用。如果所有线程都在工作,又有新的任务,则会创建新的线程。

  • newSingleThreadScheduledExecutor(): 可调度的单线程

  • newScheduledThreadPool(int n): 可调度的线程池

    • schedule(Runnable task,long delay,TimeUnit unit)

    • scheduleAtFixedRate(Runnable task, long InitDelay,long period,TimeUnit)

    • scheduleWithFixedDelay(Runnable task,long IniDelay,long delay,TimeUnit)

TheadPoolExecutor的实现(实现ExecutorService接口)

ThreadPoolExecutor是上述的各种线程池的实现类,在处理大量的异步任务时会有很好的性能。

public ThreadPoolExecutor(int corePoolSize,                          //指定线程池中的线程数量                          int maximumPoolSize,                       //最大线程数量                          long keepAliveTime,                        //当超过corePoolSize,多余线程会存活的时间                          TimeUnit unit,                          BlockingQueue<Runnable> workQueue,         //提交了但尚未被执行的任务                          ThreadFactory threadFactory,               //用于创建线程,建议默认                          RejectExectionHandler handler)             //当任务太多,用什么策略去拒绝任务ExecutorService es = new ThreadPoolThread(5,5,0L,TimeUnit.MILLISECONDS,                                 new LinkedBlockingQueue<Runnable>(10),                                 Executors.defaultThreadFactory(),                                 new RejectExecutionHandler(){                                     @Override                                     public void rejectExecution(Runnable r,ThreadPoolExecutor ex){                                         System.out.println("discard it");                                     }                                 });for(int i = 0;i < Integer.MAX_VALUE;i++){    es.submit(task);}

workQueue参数:

  • SynchronousQueue: 直接提交的队列,每一个插入操作需要等待一个相应的删除操作,每一个删除操作需要等待相应的插入操作。通常需要设置很大的maximumPoolSize, 否则会很容易执行拒绝策略。

  • ArrayBlockingQueue: 有界的任务队列,public ArrayBlockingQueue(int capacity)当使用有界的任务队列时,若有新的任务,如果线程池的实际线程数小于corePoolSize会优先创建新线程,若大于,则任务会加入队列。若任务队列已满,会创建新线程,但大于maximumPoolSize,则会执行拒绝策略。

  • LinkedBlockingQueue: 无界的任务队列,如果线程池的实际线程数小于corePoolSize会优先创建新线程。若大于则任务会入队列,无限地入队列。

  • PriorityBlockingQueue: 优先任务队列,是个特殊的无界任务队列。

public void execute(Runnable command) {        if (command == null)            throw new NullPointerException();        /*         * Proceed in 3 steps:         *         * 1. If fewer than corePoolSize threads are running, try to         * start a new thread with the given command as its first         * task.  The call to addWorker atomically checks runState and         * workerCount, and so prevents false alarms that would add         * threads when it shouldn't, by returning false.         *         * 2. If a task can be successfully queued, then we still need         * to double-check whether we should have added a thread         * (because existing ones died since last checking) or that         * the pool shut down since entry into this method. So we         * recheck state and if necessary roll back the enqueuing if         * stopped, or start a new thread if there are none.         *         * 3. If we cannot queue task, then we try to add a new         * thread.  If it fails, we know we are shut down or saturated         * and so reject the task.         */        int c = ctl.get();        if (workerCountOf(c) < corePoolSize) {            if (addWorker(command, true))                return;            c = ctl.get();        }        if (isRunning(c) && workQueue.offer(command)) {            int recheck = ctl.get();            if (! isRunning(recheck) && remove(command))                reject(command);            else if (workerCountOf(recheck) == 0)                addWorker(null, false);        }        else if (!addWorker(command, false))            reject(command);    }

拒绝策略接口RejectedExecutionHandler

  • AbortPolicy: 会直接抛出异常,阻止系统正常工作

  • CallerRunsPolicy: 只要线程池未关闭,该策略直接在调用者线程中,运行当前被丢弃的任务,但不是真的会丢弃线程。

  • DiscardOledestPolicy: 该策略将丢弃最老的一个请求,也就是即将被执行的一个任务,并尝试再次提交当前任务。

  • DiscardPolicy: 该策略默默地丢弃无法处理的任务,不予任何处理。

关闭线程池:

  • shutdown(): 使未完成的任务继续,但不再添加任务了

  • shutdownNow(): 中断所有任务,并抛出InterruptionExeception异常,线程状态转变为打断状态,

原创粉丝点击