什么是线程池?

  • java线程池是将大量的线程集中管理的类, 包括对线程的创建, 资源的管理, 线程生命周期的管理。
  • 当系统中存在大量的异步任务的时候就考虑使用java线程池管理所有的线程, 从而减少系统资源的开销。

阿里的开发手册规范

  • 线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这样 的处理方式让写的人更加明确线程池的运行规则,规避资源耗尽的风险。
  • Executors 返回的线程池对象的弊端如下:
    • FixedThreadPool 和 SingleThreadPool: 允许的请求队列长度为 Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM。
    • CachedThreadPool 和 ScheduledThreadPool: 允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。

线程池的创建

  • new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime, TimeUnit unit,BlockingQueue workQueue,RejectedExecutionHandler handler)

    • corePoolSize: 线程池维护线程的最少数量
    • maximumPoolSize: 线程池维护线程所允许的空闲时间
    • unit: 线程池维护线程锁允许的空闲时间的单位
    • workQueue: 线程池锁使用的缓冲队列
    • handler: 线程池对拒绝任务的处理策略

添加任务到线程池

  • 通过execute(Runnable) 方法添加到线程池, 任务就是一个Runnable类型的对象, 任务的执行方法就是Runnable类型对象的run()方法。

  • 当一个任务通过execute(Runnable) 方法欲添加到线程池时:

    • 如果此时线程池中线程的数量小于corePoolSize, 即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。
    • 如果此时线程池中的数量等于 corePoolSize,但是缓冲队列 workQueue未满,那么任务被放入缓冲队列
    • 如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maximumPoolSize,建新的线程来处理被添加的任务。
    • 如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maximumPoolSize,那么通过 handler所指定的策略来处理此任务。
  • 也就是说:

    • 处理任务的优先级为:

      • 核心线程corePoolSize、任务队列workQueue、最大线程maximumPoolSize,如果三者都满了,使用handler处理被拒绝的任务。
  • 当线程池中的线程数量大于 corePoolSize时,如果某线程空闲时间超过keepAliveTime,线程将被终止。这样,线程池可以动态的调整池中的线程数。

  • unit可选的参数为java.util.concurrent.TimeUnit中的几个静态属性:NANOSECONDS、MICROSECONDS、MILLISECONDS、SECONDS。

  • workQueue常用的是:java.util.concurrent.ArrayBlockingQueue

  • handler的四个选择:

    • ThreadPoolExecutor.AbortPolicy() [直译过来流产计划?]

      • 抛出 java.util.concurrent.RejectedExecutionException异常

         /**
        * A handler for rejected tasks that throws a
        * {@code RejectedExecutionException}.
        */
        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());
        }
        }
    • ThreadPoolExecutor.CallerRunsPolicy()

      • 重试添加当前的任务,它会自动重复调用execute()方法

        /**
        * 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 {
        /**
        * 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.
        * 在调用者的线程中执行任务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) {
        if (!e.isShutdown()) {
        r.run();
        }
        }
        }
    • ThreadPoolExecutor.DiscardOldestPolicy()

      • 抛弃旧的任务

         /**
        * 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 {
        /**
        * 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.
        * 获取并忽视下一个执行器会执行的任务, 如果其中一个是当前可获取的, 并且
        *多次重试执行过任务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) {
        if (!e.isShutdown()) {
        e.getQueue().poll();
        e.execute(r);
        }
        }
        }
        }
    • ThreadPoolExecutor.DiscardPolicy()

      • 抛弃当前的任务

        /**
        * A handler for rejected tasks that silently discards the
        * rejected task.
        */
        public static class DiscardPolicy implements RejectedExecutionHandler {
        /**
        * Creates a {@code DiscardPolicy}.
        */
        public DiscardPolicy() { } /**
        * Does nothing, which has the effect of discarding task r.
        * 什么都不做, 就有抛弃任务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) {
        }
        }

测试线程池Demo

package com.ronnie;

import java.io.Serializable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; public class ThreadPoolDemo {
private static int produceTaskSleepTime = 5;
private static int consumeTaskSleepTime = 5000;
private static int produceTaskMaxNumber = 20; // 定义最大添加20个线程到线程池中 /**
* 线程池执行的任务
*/
public static class ThreadPoolTask implements Runnable, Serializable{
private static final long serialVersionUID = 0;
// 保存任务所需要的数据
private Object threadPoolTaskData;
ThreadPoolTask(Object works){
this.threadPoolTaskData = works;
}
@Override
public void run() {
// 处理一个任务
System.out.println(threadPoolTaskData + "started......");
try {
// 便于观察, 等待一段时间
Thread.sleep(consumeTaskSleepTime);
} catch (Exception e){
e.printStackTrace();
}
threadPoolTaskData = null;
} public Object getTask(){
return this.threadPoolTaskData;
}
} public static void main(String[] args) {
// 构造一个线程池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(6, 12, 9,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(6), new ThreadPoolExecutor.DiscardOldestPolicy()); for (int i = 1; i <= produceTaskMaxNumber; i++){
try {
// 创建一个任务并将其加入线程池
String work = "work@: " + i;
System.out.println("put: " + work);
threadPool.execute(new ThreadPoolTask(work));
// 等待一会儿, 便于观察
Thread.sleep(produceTaskSleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
}
  • 执行结果

    put: work@: 1
    work@: 1started......
    put: work@: 2
    work@: 2started......
    put: work@: 3
    work@: 3started......
    put: work@: 4
    work@: 4started......
    put: work@: 5
    work@: 5started......
    put: work@: 6
    work@: 6started......
    put: work@: 7
    put: work@: 8
    put: work@: 9
    put: work@: 10
    put: work@: 11
    put: work@: 12
    put: work@: 13
    work@: 13started......
    put: work@: 14
    work@: 14started......
    put: work@: 15
    work@: 15started......
    put: work@: 16
    work@: 16started......
    put: work@: 17
    work@: 17started......
    put: work@: 18
    work@: 18started......
    put: work@: 19
    put: work@: 20
    work@: 9started......
    work@: 10started......
    work@: 11started......
    work@: 12started......
    work@: 19started......
    work@: 20started......

Java线程池 ThreadPoolExecutor类的更多相关文章

  1. Java线程池ThreadPoolExecutor类源码分析

    前面我们在java线程池ThreadPoolExecutor类使用详解中对ThreadPoolExector线程池类的使用进行了详细阐述,这篇文章我们对其具体的源码进行一下分析和总结: 首先我们看下T ...

  2. java线程池ThreadPoolExecutor类使用详解

    在<阿里巴巴java开发手册>中指出了线程资源必须通过线程池提供,不允许在应用中自行显示的创建线程,这样一方面是线程的创建更加规范,可以合理控制开辟线程的数量:另一方面线程的细节管理交给线 ...

  3. Java线程池ThreadPoolExecutor使用和分析(三) - 终止线程池原理

    相关文章目录: Java线程池ThreadPoolExecutor使用和分析(一) Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理 Java线程池Thr ...

  4. Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理

    相关文章目录: Java线程池ThreadPoolExecutor使用和分析(一) Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理 Java线程池Thr ...

  5. Java线程池ThreadPoolExecutor使用和分析(一)

    相关文章目录: Java线程池ThreadPoolExecutor使用和分析(一) Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理 Java线程池Thr ...

  6. Java 线程池 ThreadPoolExecutor 的那些事儿

    线程池基础知识 ThreadPoolExecutor : 一个线程池 Executors : 线程池工厂,通过该类可以取得一个拥有特定功能的线程池 ThreadPoolExecutor类实现了Exec ...

  7. 线程池 ThreadPoolExecutor 类的源码解析

    线程池 ThreadPoolExecutor 类的源码解析: 1:数据结构的分析: private final BlockingQueue<Runnable> workQueue;  // ...

  8. java线程池ThreadPoolExecutor使用简介

    一.简介线程池类为 java.util.concurrent.ThreadPoolExecutor,常用构造方法为:ThreadPoolExecutor(int corePoolSize, int m ...

  9. 线程池ThreadPoolExecutor类的使用

    1.使用线程池的好处? 第一:降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗. 第二:提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行. 第三:提高线程的可管理性 ...

随机推荐

  1. spring cloud spring boot JPA 克隆对象修改属性后 无法正常的执行save方法进行保存或者更新

    2019-12-1220:34:58 spring cloud spring boot JPA 克隆对象修改属性后 无法正常的执行save方法进行保存或者更新 未解决

  2. 数据库转换Mysql-Oracle之建表语句

    Mysql建库语句(导出的): DROP TABLE IF EXISTS `tablename`; CREATE TABLE `tablename` ( `C_DI_CDE` varchar(40) ...

  3. Spark教程——(11)Spark程序local模式执行、cluster模式执行以及Oozie/Hue执行的设置方式

    本地执行Spark SQL程序: package com.fc //import common.util.{phoenixConnectMode, timeUtil} import org.apach ...

  4. TouchGFX

    TouchGFX让用户界面代码只占用10KB的 SRAM空间和20KB的闪存空间的C ++软件框架.有无操作系统均可

  5. spm_hrf

    a=spm_hrf(0.72); n1=MOTOR_taskdesign(1,:);cn1=conv(n1,a);plot(cn1); block design hrf

  6. python人脸对比

    import sys  import ssl  from urllib import request,parse    # client_id 为官网获取的AK, client_secret 为官网获 ...

  7. 防火墙问题 Linux系统 /etc/sysconfig/路径下无iptables文件

    虚拟机新装了一个CentOs7,然后做防火墙配置的时候找不到iptables文件,解决方法如下: 因为默认使用的是firewall作为防火墙,把他停掉装个iptable systemctl stop ...

  8. ubuntu 文件操作

    linux的文件目录是一棵目录树,默认起始位置在主文件夹(/home/city),里面有若干子文件(视频.图片.下载.桌面等) 一.文件路径(目录操作) 1.绝对路径:从根目录/写起,完整的.详细的描 ...

  9. day07 集合

    ''' list,查询过程中修改,会报错,类似java的并发修改异常 Traceback (most recent call last): File "C:/1xubenqing/pytho ...

  10. java并发:初探用户线程和守护线程

    用户线程和守护线程 用户线程 用户线程执行完,jvm退出.守护线程还是可以跑的 /** * A <i>thread</i> is a thread of execution i ...