ThreadPoolExecutor线程池

为什么使用线程池:

1、创建/销毁线程伴随着系统开销,过于频繁的创建/销毁线程,会很大程度上影响处理效率。

2、线程并发数量过多,抢占系统资源从而导致阻塞。

3、对线程进行一些简单的管理。

在java中,线程池的类为ThreadPoolExecutor,首先来看一下该类的继承关系

大抵所有的线程池都是来自于Executor接口,这个接口里面定义了线程池的抽象方法:

    void execute(Runnable command);

在Executor接口之后的是ExecutorServer接口,里面定义了一些submit()、shutdown()方法。

然后我们来看一下ThreadPoolExecutor类提供的四种构造方法:

//五个参数的构造函数
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue)

//六个参数的构造函数-1
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory)

//六个参数的构造函数-2
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          RejectedExecutionHandler handler)

//七个参数的构造函数
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler)

方法中的参数:

int corePoolSize  线程池中核心线程大小

  在线程池中的线程小于核心线程数时,则新建的线程属于核心线程,否则属于非核心线程。默认情况下,核心线程会一直存货于线程池,即使什么也不做。但如果指定类中的allowCoreThreadTimeOut为true,则核心线程闲置一定时间后也会被销毁,具体时间,由参数指定。

int maximumPoolSize  线程池中最大线程数

  线程池中存在的线程数量不会超过最大线程数,如果在达到最大线程数后仍有新的任务需要执行,则会进行排队。

long keepAliveTime  非核心线程的最大存活时间

  线程池中的非核心线程处于闲置状态时,则会开始计时,达到指定时间后将被销毁。如果指定参数allowCoreThreadTimeOut为true,则核心线程同样适用。

TimeUnit unit  keepAliveTime的单位

  类型TimeUnit是枚举类型,包括

    NANOSECONDS : 1微毫秒 = 1微秒 / 1000

    MICROSECONDS : 1微秒 = 1毫秒 / 1000

    MILLISECONDS : 1毫秒 = 1秒 /1000

    SECONDS : 秒

    MINUTES : 分

    HOURS : 小时

    DAYS : 天

BlockingQueue<Runnable> workQueue  任务队列

  等待执行的Runnable对象所组成的队列。如果所有核心线程都正在执行,则任务会进行队列。如果队列满了,则新建非核心线程。

   常用的workQueue类型:

    SynchronousQueue:这个队列接收任务后直接提交给线程处理而不会保留它。为了避免线程数量达到maximumPoolSize而无法新建新的线程,通常将maximumPoolSize设置为Integer.MAX_VALUE,即无限大。

    LinkedBlockingQueue:这个队列接收任务后,将任务交给核心线程处理,如果没有空闲的核心线程,则会保留在队列中。由于该队列没有数量限制,因此线程数永远不会超过核心线程数,即maximumPoolSize无效。

    ArrayBlockingQueue:这个队列与LinkedBlockingQueue的区别在于有数量限制,当队列已满后将新建非核心线程,如果总线程数达到maximumPoolSize,则发生错误。

    DelayQueue:队列内元素必须实现delayed接口,即传进去的任务必须先实现delayed接口。接收到的任务会先进入队列,达到了指定的延时时间,才会执行任务。

ThreadFactory threadFactory  创建线程的方式。

  这是一个接口,new的时候需要实现Thread newThread(Runnable r)方法。

RejectedExecutionHandler handler  异常

  用来抛出异常,如发生异常,则由该异常对象抛出信息,即使不指定也会有个默认值。

向线程池添加任务

ThreadPoolExecutor.execute(Runnable command) //这个方法是在ThreadPoolExcutor中重写,没有返回结果的添加线程任务
    // 这个方法也可以被用来往线程池中添加线程任务。不同处在于它是定义在AbstractExecutorServer中,在ThreadPoolExecutor中没有再重写它。
    public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<Void> ftask = newTaskFor(task, null); 
        execute(ftask); //内部仍是调用了execute()方法。
        return ftask;
    }

ThreadPoolExecutor的策略

当一个任务被添加进线程池后:

1、线程数未达到核心线程数,新建一个核心线程数。

2、线程数已达到核心线程数,任务保留进队列。

3、线程数已达到核心线程数,任务队列已满,新建一个非核心线程数。

4、线程数已达到最大线程数,任务队列已满,抛出异常。

常见的四种线程池

(在阿里巴巴JAVA开发手册中是不建议通过Executors来创建这些配置好的线程池)

java对线程池类ThreadPoolExecutor进行了封装,提供了常用的四种线程池。这四种线程池都是或直接或间接配置ThreadPoolExecutor的参数实现。

1、CachedThreadPool()  可缓存线程池

  • 线程数无限
  • 有空闲线程则使用空闲线程,否则创建新线程
  • 一定程度上减少创建/销毁线程的开销

 创建方法

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

 源码

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

2、FixedThreadPool()  定长线程池

  • 可控制线程最大并发数
  • 超出的线程会在队列中等待

 创建方法

//nThreads => 最大线程数即maximumPoolSize
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(int nThreads);

//threadFactory => 创建线程的方法
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(int nThreads, ThreadFactory threadFactory);

源码

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

3、ScheduledTheadPool()  定长线程池

  • 支持定时周期性的执行任务

创建方法

//nThreads => 最大线程数即maximumPoolSize
ExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(int corePoolSize);

源码

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

//ScheduledThreadPoolExecutor():
public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE,
          DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
          new DelayedWorkQueue());
}

4、SingleThreadExecutor()  单线程线程池

  有且仅有一个工作线程执行任务

  所有任务按照指定顺序执行,即遵循队列的出队入队规则。

创建方法

ExecutorService singleThreadPool = Executors.newSingleThreadPool();

源码

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}

 ThreadPoolExecutor任务拒绝策略

ThreadPoolExecutor里面定义了4个静态内部类,用来标识不同的异常类型:

ThreadPoolExecutor.AbortPolicy //拒绝接收任务并抛出rejectedExecuption
ThreadPoolExecutor.DiscardPolicy //拒绝接收任务,但不抛出任何异常
ThreadPoolExecutor.DiscardOldestPolicy //将等待队列中的第一个任务抛弃,接收新的线程任务。
ThreadPoolExecutor.CallerRunsPolicy //由调用线程处理该任务。

下面我们来分别用代码测试一下这几种任务拒绝策略

    public void testThreadPoolRejectedPoicy(RejectedExecutionHandler handler) {
// 先定义一个线程池,核心线程数2,最大线程数4,非核心线程过期时间10分钟,队列最大任务数2.
ThreadPoolExecutor te
= new ThreadPoolExecutor(2,4,10, TimeUnit.MINUTES, new ArrayBlockingQueue<>(2), handler);
// 一次性添加20个任务进入线程池,由于我们配置的线程池最大只能接收6个任务,因此一旦超过6个就会触发拒绝策略
for (int i = 0; i < 20; i++) {
final int j = i; te.execute(
new Runnable() { @Override public void run() { try { System.out.println("当前线程" + Thread.currentThread() + "正在执行" + j + "!" + new Date()); Thread.sleep(5 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); }

测试第一个任务拒绝策略

AbortPolicy :
testThreadPoolRejectedPoicy(new ThreadPoolExecutor.AbortPolicy());

返回结果:线程池中添加的任务超出了6个,抛出异常,并拒绝接收,可以看到打印出来的i是从0到5。

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task Main5$1@681a9515 rejected from java.util.concurrent.ThreadPoolExecutor@3af49f1c[Running, pool size = 4, active threads = 4, queued tasks = 2, completed tasks = 0]
    at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
    at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
    at Main5.testThreadPoolRejectedPoicy(Main5.java:25)
    at Main5.main(Main5.java:14)
当前线程Thread[pool-1-thread-4,5,main]正在执行5!Thu May 09 10:37:41 CST 2019
当前线程Thread[pool-1-thread-1,5,main]正在执行0!Thu May 09 10:37:41 CST 2019
当前线程Thread[pool-1-thread-2,5,main]正在执行1!Thu May 09 10:37:41 CST 2019
当前线程Thread[pool-1-thread-3,5,main]正在执行4!Thu May 09 10:37:41 CST 2019
当前线程Thread[pool-1-thread-4,5,main]正在执行2!Thu May 09 10:37:46 CST 2019
当前线程Thread[pool-1-thread-1,5,main]正在执行3!Thu May 09 10:37:46 CST 2019

测试第二个任务拒绝策略

DiscardPolicy :
testThreadPoolRejectedPoicy(new ThreadPoolExecutor.DiscardPolicy ());

返回结果:和AbortPolicy区别只在于没有抛出异常。

当前线程Thread[pool-1-thread-2,5,main]正在执行1!Thu May 09 10:40:00 CST 2019
当前线程Thread[pool-1-thread-3,5,main]正在执行4!Thu May 09 10:40:00 CST 2019
当前线程Thread[pool-1-thread-4,5,main]正在执行5!Thu May 09 10:40:00 CST 2019
当前线程Thread[pool-1-thread-1,5,main]正在执行0!Thu May 09 10:40:00 CST 2019
当前线程Thread[pool-1-thread-3,5,main]正在执行3!Thu May 09 10:40:05 CST 2019
当前线程Thread[pool-1-thread-2,5,main]正在执行2!Thu May 09 10:40:05 CST 2019

测试第三个任务拒绝策略

DiscardOldestPolicy :
testThreadPoolRejectedPoicy(new ThreadPoolExecutor.DiscardOldestPolicy());

返回结果:在这里,首先执行前4个线程任务,同时还会有2两个线程任务存放在队列中等待竞争。此时第7个任务进来,将队列中的第一个任务丢弃,将第7个任务添加进队列,第8个,第9个一直如此,直到第19个任务被添加进来,此时队列中的两个任务只剩下了18和19。其余的任务已经都被丢弃。因此等到前面4个任务执行完成后,第18和19个任务开始执行。

当前线程Thread[pool-1-thread-3,5,main]正在执行4!Thu May 09 10:41:36 CST 2019
当前线程Thread[pool-1-thread-1,5,main]正在执行0!Thu May 09 10:41:36 CST 2019
当前线程Thread[pool-1-thread-2,5,main]正在执行1!Thu May 09 10:41:36 CST 2019
当前线程Thread[pool-1-thread-4,5,main]正在执行5!Thu May 09 10:41:36 CST 2019
当前线程Thread[pool-1-thread-3,5,main]正在执行18!Thu May 09 10:41:41 CST 2019
当前线程Thread[pool-1-thread-2,5,main]正在执行19!Thu May 09 10:41:41 CST 2019

测试第四个任务拒绝策略:

CallerRunsPolicy :
testThreadPoolRejectedPoicy(new ThreadPoolExecutor.CallerRunsPolicy());

返回结果:任务比较多就只取了前面部分。可以看到线程池中一直有4个线程在执行任务,并且队列中也保持了两个任务等待。此时添加了新的任务进来,会交由当前线程(我是在main方法中执行,因此是main线程)执行任务。当main线程执行任务的时候,会与往线程池中添加新任务处于竞争状态。在这种情况下,20个线程任务会被一直执行到全部完成。

当前线程Thread[pool-1-thread-3,5,main]正在执行4!Thu May 09 11:06:43 CST 2019
当前线程Thread[pool-1-thread-2,5,main]正在执行1!Thu May 09 11:06:43 CST 2019
当前线程Thread[pool-1-thread-4,5,main]正在执行5!Thu May 09 11:06:43 CST 2019
当前线程Thread[pool-1-thread-1,5,main]正在执行0!Thu May 09 11:06:43 CST 2019
当前线程Thread[main,5,main]正在执行6!Thu May 09 11:06:43 CST 2019
当前线程Thread[pool-1-thread-2,5,main]正在执行3!Thu May 09 11:06:48 CST 2019
当前线程Thread[pool-1-thread-3,5,main]正在执行2!Thu May 09 11:06:48 CST 2019
当前线程Thread[pool-1-thread-4,5,main]正在执行7!Thu May 09 11:06:48 CST 2019
当前线程Thread[pool-1-thread-1,5,main]正在执行8!Thu May 09 11:06:48 CST 2019
当前线程Thread[main,5,main]正在执行9!Thu May 09 11:06:48 CST 2019
……
……

原文链接:https://www.jianshu.com/p/210eab345423

原文地址:https://www.cnblogs.com/yxth/p/8467087.html