一、线程池的介绍

线程池一种性能优化的重要手段。优化点在于创建线程和销毁线程会带来资源和时间上的消耗,而且线程池可以对线程进行管理,则可以减少这种损耗。

使用线程池的好处如下:

  • 降低资源的消耗
  • 提高响应的速度
  • 提高线程的可管理性

二、线程池的使用


public class ThreadPoolExecutorDemo { static class Worker implements Runnable{ @Override
public void run() {
try {
Thread.sleep(10_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行任务"+Thread.currentThread().getName());
}
} public static void main(String[] args) { Worker worker1 = new Worker();
Worker worker2 = new Worker();
Worker worker3 = new Worker();
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.submit(worker1);
executorService.submit(worker2);
executorService.submit(worker3);
executorService.shutdown();
} }

运行结果



如果将线程池的大小设置为3, Executors.newFixedThreadPool(3);,则运行结果如下:

public static void main(String[] args) {

        Worker worker1 = new Worker();
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(4));
for(int i=0;i<9;i++) {
executor.submit(worker1);
}
executor.shutdown();
}

运行结果

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@677327b6 rejected from java.util.concurrent.ThreadPoolExecutor@14ae5a5[Running, pool size = 2, active threads = 2, queued tasks = 4, 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 java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at com.fonxian.baseuse.ThreadPoolExecutorDemo.main(ThreadPoolExecutorDemo.java:27)
执行任务pool-1-thread-2
执行任务pool-1-thread-1
执行任务pool-1-thread-2
执行任务pool-1-thread-1
执行任务pool-1-thread-1
执行任务pool-1-thread-2

实际生产开发中,不允许使用Executors,而是通过ThreadPoolExecutor的方式创建,这样能规避资源耗尽的风险。

三、线程池的实现原理

  1. 线程池先判断核心线程池中的所有线程是否都在执行任务,若否,创建新任务,若是进入下一个流程
  2. 线程池判断工作队列是否已满,未满,任务加入队列,若满,进入下个流程
  3. 线程池判断线程池中的线程是否都在执行任务,若是,则创建新任务,若否,交给饱和策略处理任务。

四、ThreadPoolExecutor源码

2.1 类依赖关系

2.2 源码解析

成员变量


public class ThreadPoolExecutor extends AbstractExecutorService { //工作队列
private final BlockingQueue<Runnable> workQueue; //核心线程池大小
private volatile int corePoolSize; //最大线程池大小
private volatile int maximumPoolSize; private static final RejectedExecutionHandler defaultHandler =
new AbortPolicy(); }

execute方法


//ctl, is an atomic integer packing two conceptual fields
//workerCount, indicating the effective number of threads
//runState, indicating whether running, shutting down etc
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0)); /*
* 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.
*/
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
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);
}
//抛出RejectedExecutionException异常
else if (!addWorker(command, false))
reject(command);
}

构造方法

/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} or {@code handler} is null
*/
public ThreadPoolExecutor(int corePoolSize,//核心线程池大小
int maximumPoolSize,//最大线程池大小
long keepAliveTime,//线程活动保持时间
TimeUnit unit,//线程活动保持时间单位
BlockingQueue<Runnable> 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.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}

keepAliveTime有何作用?

线程活动保持时间。线程池的工作线程空闲后,保持存活的时间。如果任务多,每个任务执行时间短,可以调大时间,提高线程的利用率。

RejectedExecutionHandler对象都有哪些选择?

ThreadFactory对象都有哪些选择?

工作队列都有哪些选择?

  • ArrayBlockingQueue

    • 一个由数组结构组成的有界阻塞队列。
  • LinkedBlockingQueue
    • 一个由链表结构组成的有界阻塞队列
  • SynchronousQueue
    • 一个不存储元素的阻塞队列
  • PriorityBlockingQueue
    • 一个支持优先级排序的无界阻塞队列。

execute()和submit()有何区别?

submit()用于提交需要返回值的任务。调用该方法会返回一个Future对象。future.get()获取返回值,get()方法会阻塞当前进程直到任务完成,而get(long timeout,TimeUnit unit)会阻塞一段时间。

如何关闭线程池?

调用shutdown()或shutdownNow()关闭线程池。

shutdown()和shutdownNow()有什么区别。shutdown需要等所有任务完成后,关闭线程池。而shutdownNow()会直接关闭线程池。

五、如何合理配置线程池

CPU密集型的任务,尽可能分配少一点的线程数。IO密集型的任务,尽可能分配多一点的线程数。

参考文档

《Java并发编程的艺术》

Java并发--深入理解线程池

线程池没你想的那么简单

再聊线程池

Java核心复习——线程池ThreadPoolExecutor源码分析的更多相关文章

  1. Java并发之线程池ThreadPoolExecutor源码分析学习

    线程池学习 以下所有内容以及源码分析都是基于JDK1.8的,请知悉. 我写博客就真的比较没有顺序了,这可能跟我的学习方式有关,我自己也觉得这样挺不好的,但是没办法说服自己去改变,所以也只能这样想到什么 ...

  2. Python线程池ThreadPoolExecutor源码分析

    在学习concurrent库时遇到了一些问题,后来搞清楚了,这里记录一下 先看个例子: import time from concurrent.futures import ThreadPoolExe ...

  3. java内置线程池ThreadPoolExecutor源码学习记录

    背景 公司业务性能优化,使用java自带的Executors.newFixedThreadPool()方法生成线程池.但是其内部定义的LinkedBlockingQueue容量是Integer.MAX ...

  4. 线程池ThreadPoolExecutor源码分析

    在阿里编程规约中关于线程池强制了两点,如下: [强制]线程资源必须通过线程池提供,不允许在应用中自行显式创建线程.说明:使用线程池的好处是减少在创建和销毁线程上所消耗的时间以及系统资源的开销,解决资源 ...

  5. java线程池ThreadPoolExector源码分析

    java线程池ThreadPoolExector源码分析 今天研究了下ThreadPoolExector源码,大致上总结了以下几点跟大家分享下: 一.ThreadPoolExector几个主要变量 先 ...

  6. 【Java并发编程】21、线程池ThreadPoolExecutor源码解析

    一.前言 JUC这部分还有线程池这一块没有分析,需要抓紧时间分析,下面开始ThreadPoolExecutor,其是线程池的基础,分析完了这个类会简化之后的分析,线程池可以解决两个不同问题:由于减少了 ...

  7. 线程池ThreadPoolExecutor源码解读研究(JDK1.8)

    一.什么是线程池 为什么要使用线程池?在多线程并发开发中,线程的数量较多,且每个线程执行一定的时间后就结束了,下一个线程任务到来还需要重新创建线程,这样线程数量特别庞大的时候,频繁的创建线程和销毁线程 ...

  8. Java并发包源码学习系列:线程池ThreadPoolExecutor源码解析

    目录 ThreadPoolExecutor概述 线程池解决的优点 线程池处理流程 创建线程池 重要常量及字段 线程池的五种状态及转换 ThreadPoolExecutor构造参数及参数意义 Work类 ...

  9. Java调度线程池ScheduledThreadPoolExecutor源码分析

    最近新接手的项目里大量使用了ScheduledThreadPoolExecutor类去执行一些定时任务,之前一直没有机会研究这个类的源码,这次趁着机会好好研读一下. 该类主要还是基于ThreadPoo ...

随机推荐

  1. 【转载】C#使用is关键字检查对象是否与给定类型兼容

    在C#的编程开发过程中,很多时候涉及到数据类型的转换,如果强行转换数据类型,有时候可能会出现程序运行时错误,C#语言中提供了is关键字可以检查对象是否与给定类型兼容,可先判断类型兼容后再进行对象的转换 ...

  2. 【转载】网站配置Https证书系列(二):IIS服务器给网站配置Https证书

    针对网站的Https证书,即SSL证书,腾讯云.阿里云都提供了免费的SSL证书申请,SSL证书申请下来后,就需要将SSL证书配置到网站中,如果网站使用的Web服务器是IIS服务器,则需要在IIS服务器 ...

  3. Traceback (most recent call last): File "../zubax_chibios/tools/make_boot_descriptor.py", line 251

    出现如下错误: Traceback (most recent call last): File "../zubax_chibios/tools/make_boot_descriptor.py ...

  4. URLErro和HTTPError

    url error URLError 产生的原因主要有: 没有网络连接 服务器连接失败 找不到指定的服务器 我们可以用try except语句来捕获相应的异常 from urllib import r ...

  5. kubeadm init初始化报错解决,亲测

    [preflight] You can also perform this action in beforehand using 'kubeadm config images pull' error ...

  6. unittest 运行slenium(三)---通过数据驱动形式运行用例

    一: 获取数据 获取用例所在位置,通过OpenExcelPandas来读取用例里面的全部数据.通过某个列名来创建新的序号. 并将结果转换成list类型,将其作为ddt数据的来源. 1.  在test文 ...

  7. git命令——git commit

    功能 将暂存区中的更改记录到仓库. 加到staging area里面的文件,是表示已经准备好commit的.所以在commit修改之前,务必确定所有修改文件都是staged的.对于unstaged的文 ...

  8. Python高阶用法总结

    目录 1. lambda匿名函数 1.1 函数式编程 1.2 应用在闭包 2. 列表解析式 3. enumerate内建函数 4. 迭代器与生成器 4.1 迭代器 4.3 生成器 5. 装饰器 前言: ...

  9. js中的forEach和map的区别

    我们先来看两者之间的相同之处 var arr = ['a','b','c','d']; arr.forEach(function(item,index,arr){ //item表示数组中的每一项,in ...

  10. kubbernetes Flannel网络部署(五)

    一.Flannel生成证书 1.创建Flannel生成证书的文件 [root@linux-node1 ~]# vim flanneld-csr.json { "CN": " ...