Java线程池

一、什么是线程池?

线程的创建和销毁对于系统来说是一种较大的开销,线程池通过多个任务重用线程,线程创建的开销就被分摊到了多个任务上,而且请求到达时线程已经存在,消除了等待线程创建带来的延迟,使得程序响应更快。

二、线程池的优点是什么?

线程池主要用来解决线程生命周期开销问题和资源不足问题。如果每当一个请求到达就创建一个新线程,开销是挺大的,甚至在创建和销毁线程上花费的时间和消耗的资源要大于处理用户请求的时间和资源。另外如果创建线程太多,系统会由于过度消耗内存和切换过度频繁导致系统资源不足。因而可以通过线程池尽可能减少创建和销毁线程的次数,利用已有的对象进行服务。

三、线程池实现类

JDK中提供了java.util.concurrent.ThreadPoolExecutor类来实现线程池,其构造方法如下:

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue 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.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

我们先对构造方法中的参数进行介绍:

1、int corePoolSize

核心池的大小,默认情况下创建线程池之后线程池没有线程,而是等待任务到来才创建线程去执行任务,除非是调用了prestartAllCoreThreads()方法,进行线程的预创建,创建corePoolSize个线程。

public int prestartAllCoreThreads() {
        int n = 0;
        while (addWorker(null, true))
            ++n;
        return n;
    }

2、int maximumPoolSize

线程池最大线程个数,表示线程池中最多能创建的线程个数

3、long keepAliveTime

表示线程多久没有任务执行就会被销毁
默认情况下,当线程数量大于corePoolSize时,keepAliveTime才会生效,销毁线程池中线程直到线程数量不大于corePoolSize
但是如果调用了allowCoreThreadTimeOut(boolean)方法,传入参数为true时,如注释所说:核心线程也会被销毁,直到线程数量为0。

/**
     * If false (default), core threads stay alive even when idle.
     * If true, core threads use keepAliveTime to time out waiting
     * for work.
     *如果为false(默认值),则即使处于空闲状态,核心线程也保持活动 
     *状态。如果为true,则核心线程使用keepAliveTime来超时等待工作。
     */
private volatile boolean allowCoreThreadTimeOut;

public void allowCoreThreadTimeOut(boolean value) {
        if (value && keepAliveTime <= 0)
            throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
        if (value != allowCoreThreadTimeOut) {
            allowCoreThreadTimeOut = value;
            if (value)
                //销毁空闲线程
                interruptIdleWorkers();
        }
    }

4、TimeUnit unit

上一个参数keepAliveTime的时间单位,有7种静态属性取值:

        TimeUnit.DAYS;          //天
        TimeUnit.HOURS;         //小时
        TimeUnit.MINUTES;       //分钟
        TimeUnit.SECONDS;       //秒
        TimeUnit.MILLISECONDS;  //毫秒
        TimeUnit.MICROSECONDS;  //微秒
        TimeUnit.NANOSECONDS;   //纳秒

5、BlockingQueue workQueue

阻塞队列,用来存储等待执行的任务,有以下三种:
SynchronousQueue(默认)直接提交策略;
LinkedBlockingQueue无界队列策略;
ArrayBlockingQueue有界队列策略。

(1)、SynchronousQueue(默认)直接提交策略

工作队列不保存任何的任务等待执行,而是直接提交给线程进行执行;如果没有可用于立即执行任务的线程,则会创建一个新的线程来执行。此策略下maximumPoolSize将会失效。

(2)、LinkedBlockingQueue无界队列策略

无界指的是工作队列大小,可以指定大小,如果不指定,默认为Integer.MAX_VALUE,如果添加速度大于删除速度的时候,有可能会内存溢出。

(3)、ArrayBlockingQueue有界队列策略

有界也就意味着,它的大小是有限制的。所以在创建 ArrayBlockingQueue 时,必须要给它指定一个队列的大小;可以防止资源耗尽的情况发生。

6、ThreadFactory threadFactory

线程工厂,用来创建线程的工厂类

ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().
        setNameFormat("demo-pool-%d").build();

7、RejectedExecutionHandler handler

线程池拒绝策略,当线程池的任务缓存队列已满并且线程池中的线程数目达到maximumPoolSize,如果还有任务到来就会采取任务拒绝策略,有以下几种:
(1)、AbortPolicy
java线程池默认的阻塞策略,即不执行此新任务,而且直接抛出一个运行时异常(RejectedExecutionException

//丢弃任务并抛出RejectedExecutionException异常。
public static class AbortPolicy implements RejectedExecutionHandler {  
    public AbortPolicy() { }  
    // 抛出异常  
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {  
        throw new RejectedExecutionException("Task " + r.toString() +  " rejected from " +  e.toString());  
    }  
}  

(2)、DiscardPolicy
直接丢弃任务,不执行,但是不抛出异常

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) {
        }
    }

(3)、DiscardOldestPolicy
当有任务添加到线程池被拒绝时,线程池会丢弃阻塞队列中位于头部的任务,将被拒绝的任务添加到末尾,然后重试执行程序,如果再次失败,则重复此过程

public static class DiscardOldestPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardOldestPolicy} for the given executor.
         */
        public DiscardOldestPolicy() { }

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

(4)、CallerRunsPolicy
由调用线程来执行被拒绝的任务,如果执行程序已关闭,则会丢弃该任务

public static class CallerRunsPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code CallerRunsPolicy}.
         */
        public CallerRunsPolicy() { }

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

你可能感兴趣的:(Java线程池)