什么是线程池?

  • 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. js 原生url编码

    参考:http://www.runoob.com/jsref/jsref-decodeuricomponent.html

  2. scrollView嵌套

    需求:底部是一个scrollView,上面放着一小块的百度地图查看view.如果用户手指放在地图查看view上,就滚动地图查看view:如果是放在底部的scrollView上滚动,那就滚动底部的scr ...

  3. leetcode刷题-- 3.二分查找

    二分查找 正常实现 题解 public int binarySearch(int[] nums, int key) { int l = 0, h = nums.length - 1; while (l ...

  4. 《React后台管理系统实战 :四》产品分类管理页:添加产品分类、修改(更新)产品分类

    一.静态页面 目录结构 F:\Test\react-demo\admin-client\src\pages\admin\category add-cate-form.jsx index.jsx ind ...

  5. [网络必学]TCP/IP四层模型讲解【笔记整理通俗易懂版】

    OSI七层模型     表示层:用来解码不同的格式为机器语言,以及其他功能. 会话层:判断是否需要网络传输. 传输层:识别端口来指定服务器,如指定80端口的www服务. 网络层:提供逻辑地址选路,即发 ...

  6. Metric类型

    Metric类型 在上一小节中我们带领读者了解了Prometheus的底层数据模型,在Prometheus的存储实现上所有的监控样本都是以time-series的形式保存在Prometheus内存的T ...

  7. 树莓派中实现ll命令

    用管了centos的童鞋们,到了一个没有ll命令的环境里,那是多么的痛苦,在baidu后,将实现方法记录如下 方法一: echo "alias ll='ls -l'" >&g ...

  8. Android 4.1 设置默认开机动态壁纸

    最新在对Android 4.1做一些定制性的工作,刚好遇到了设置第三方动态壁纸为默认启动壁纸的问题,遂做笔记如下. 需要修改的文件为: 找到SourceCode/framework/base/core ...

  9. C++ 标准模板库STL 队列 queue 使用方法与应用介绍

    C++ 标准模板库STL 队列 queue 使用方法与应用介绍 queue queue模板类的定义在<queue>头文件中. 与stack模板类很相似,queue模板类也需要两个模板参数, ...

  10. 自定义sort排序

    java的sort自定义: 1.排序对象必须是封装类而不能是基本数据类型: 2.调用Arrays.sort(array, left, right, cmp)进行排序,array为数组,left.rig ...