Javajava 线程池 Javajava 线程池

java多线程实例下载
[问题点数:0分]
本版专家分:0
结帖率 29.25%
CSDN今日推荐
匿名用户不能发表回复!|
CSDN今日推荐如果对什么是线程、什么是进程仍存有疑惑,请先Google之,因为这两个概念不在本文的范围之内。
用多线程只有一个目的,那就是更好的利用cpu的资源,因为所有的多线程代码都可以用单线程来实现。说这个话其实只有一半对,因为反应&多角色&的程序代码,最起码每个角色要给他一个线程吧,否则连实际场景都无法模拟,当然也没法说能用单线程来实现:比如最常见的&生产者,消费者模型&。
很多人都对其中的一些概念不够明确,如同步、并发等等,让我们先建立一个数据字典,以免产生误会。
多线程:指的是这个程序(一个进程)运行时产生了不止一个线程
并行与并发:
并行:多个cpu实例或者多台机器同时执行一段处理逻辑,是真正的同时。
并发:通过cpu调度算法,让用户看上去同时执行,实际上从cpu操作层面不是真正的同时。并发往往在场景中有公用的资源,那么针对这个公用的资源往往产生瓶颈,我们会用TPS或者QPS来反应这个系统的处理能力。
并发与并行
线程安全:经常用来描绘一段代码。指在并发的情况之下,该代码经过多线程使用,线程的调度顺序不影响任何结果。这个时候使用多线程,我们只需要关注系统的内存,cpu是不是够用即可。反过来,线程不安全就意味着线程的调度顺序会影响最终结果,如不加事务的转账代码:
void transferMoney(User from, User to, float amount){
to.setMoney(to.getBalance() + amount);
from.setMoney(from.getBalance() - amount);
同步:Java中的同步指的是通过人为的控制和调度,保证共享资源的多线程访问成为线程安全,来保证结果的准确。如上面的代码简单加入@synchronized关键字。在保证结果准确的同时,提高性能,才是优秀的程序。线程安全的优先级高于性能。
好了,让我们开始吧。我准备分成几部分来总结涉及到多线程的内容:
扎好马步:线程的状态
内功心法:每个对象都有的方法(机制)
太祖长拳:基本线程类
九阴真经:高级多线程控制类
扎好马步:线程的状态
先来两张图:
线程状态转换
各种状态一目了然,值得一提的是"blocked"这个状态:线程在Running的过程中可能会遇到阻塞(Blocked)情况
调用join()和sleep()方法,sleep()时间结束或被打断,join()中断,IO完成都会回到Runnable状态,等待JVM的调度。
调用wait(),使该线程处于等待池(wait blocked pool),直到notify()/notifyAll(),线程被唤醒被放到锁定池(lock blocked pool ),释放同步锁使线程回到可运行状态(Runnable)
对Running状态的线程加同步锁(Synchronized)使其进入(lock blocked pool ),同步锁被释放进入可运行状态(Runnable)。
此外,在runnable状态的线程是处于被调度的线程,此时的调度顺序是不一定的。Thread类中的yield方法可以让一个running状态的线程转入runnable。
内功心法:每个对象都有的方法(机制)
synchronized, wait, notify 是任何对象都具有的同步工具。让我们先来了解他们
他们是应用于同步问题的人工线程调度工具。讲其本质,首先就要明确monitor的概念,Java中的每个对象都有一个监视器,来监测并发代码的重入。在非多线程编码时该监视器不发挥作用,反之如果在synchronized 范围内,监视器发挥作用。
wait/notify必须存在于synchronized块中。并且,这三个关键字针对的是同一个监视器(某对象的监视器)。这意味着wait之后,其他线程可以进入同步块执行。
当某代码并不持有监视器的使用权时(如图中5的状态,即脱离同步块)去wait或notify,会抛出java.lang.IllegalMonitorStateException。也包括在synchronized块中去调用另一个对象的wait/notify,因为不同对象的监视器不同,同样会抛出此异常。
再讲用法:
synchronized单独使用:
代码块:如下,在多线程环境下,synchronized块中的方法获取了lock实例的monitor,如果实例相同,那么只有一个线程能执行该块内容
public class Thread1 implements Runnable {
public void run() {
synchronized(lock){
..do something
直接用于方法: 相当于上面代码中用lock来锁定的效果,实际获取的是Thread1类的monitor。更进一步,如果修饰的是static方法,则锁定该类所有实例。
public class Thread1 implements Runnable {
public synchronized void run() {
..do something
synchronized, wait, notify结合:典型场景生产者消费者问题
* 生产者生产出来的产品交给店员
public synchronized void produce()
if(this.product &= MAX_PRODUCT)
System.out.println("产品已满,请稍候再生产");
catch(InterruptedException e)
e.printStackTrace();
this.product++;
System.out.println("生产者生产第" + this.product + "个产品.");
notifyAll();
//通知等待区的消费者可以取出产品了
* 消费者从店员取产品
public synchronized void consume()
if(this.product &= MIN_PRODUCT)
System.out.println("缺货,稍候再取");
catch (InterruptedException e)
e.printStackTrace();
System.out.println("消费者取走了第" + this.product + "个产品.");
this.product--;
notifyAll();
//通知等待去的生产者可以生产产品了
多线程的内存模型:main memory(主存)、working memory(线程栈),在处理数据时,线程会把值从主存load到本地栈,完成操作后再save回去(volatile关键词的作用:每次针对该变量的操作都激发一次load and save)。
针对多线程使用的变量如果不是volatile或者final修饰的,很有可能产生不可预知的结果(另一个线程修改了这个值,但是之后在某线程看到的是修改之前的值)。其实道理上讲同一实例的同一属性本身只有一个副本。但是多线程是会缓存值的,本质上,volatile就是不去缓存,直接取值。在线程安全的情况下加volatile会牺牲性能。
太祖长拳:基本线程类
基本线程类指的是Thread类,Runnable接口,Callable接口Thread 类实现了Runnable接口,启动一个线程的方法:
 MyThread my = new MyThread();
  my.start();
Thread类相关方法:
//当前线程可转让cpu控制权,让别的就绪状态线程运行(切换)
public static Thread.yield()
//暂停一段时间
public static Thread.sleep()
//在一个线程中调用other.join(),将等待other执行完后才继续本线程。    
public join()
//后两个函数皆可以被打断
public interrupte()
关于中断:它并不像stop方法那样会中断一个正在运行的线程。线程会不时地检测中断标识位,以判断线程是否应该被中断(中断标识值是否为true)。终端只会影响到wait状态、sleep状态和join状态。被打断的线程会抛出InterruptedException。Thread.interrupted()检查当前线程是否发生中断,返回booleansynchronized在获锁的过程中是不能被中断的。
中断是一个状态!interrupt()方法只是将这个状态置为true而已。所以说正常运行的程序不去检测状态,就不会终止,而wait等阻塞方法会去检查并抛出异常。如果在正常运行的程序中添加while(!Thread.interrupted()) ,则同样可以在中断后离开代码体
Thread类最佳实践:写的时候最好要设置线程名称 Thread.name,并设置线程组 ThreadGroup,目的是方便管理。在出现问题的时候,打印线程栈 (jstack -pid) 一眼就可以看出是哪个线程出的问题,这个线程是干什么的。
如何获取线程中的异常
不能用try,catch来获取线程中的异常
与Thread类似
future模式:并发模式的一种,可以有两种形式,即无阻塞和阻塞,分别是isDone和get。其中Future对象用来存放该线程的返回值以及状态
ExecutorService e = Executors.newFixedThreadPool(3);
//submit方法有多重参数版本,及支持callable也能够支持runnable接口类型.
Future future = e.submit(new myCallable());
future.isDone() //return true,false 无阻塞
future.get() // return 返回值,阻塞直到该线程运行结束
九阴真经:高级多线程控制类
以上都属于内功心法,接下来是实际项目中常用到的工具了,Java1.5提供了一个非常高效实用的多线程包:java.util.concurrent, 提供了大量高级工具,可以帮助开发者编写高效、易维护、结构清晰的Java多线程程序。
1.ThreadLocal类
用处:保存线程的独立变量。对一个线程类(继承自Thread)当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。常用于用户登录控制,如记录session信息。
实现:每个Thread都持有一个TreadLocalMap类型的变量(该类是一个轻量级的Map,功能与map一样,区别是桶里放的是entry而不是entry的链表。功能还是一个map。)以本身为key,以目标为value。主要方法是get()和set(T a),set之后在map里维护一个threadLocal -& a,get时将a返回。ThreadLocal是一个特殊的容器。
2.原子类(AtomicInteger、AtomicBoolean&&)
如果使用atomic wrapper class如atomicInteger,或者使用自己保证原子的操作,则等同于synchronized
//返回值为boolean
AtomicInteger.compareAndSet(int expect,int update)
该方法可用于实现乐观锁,考虑文中最初提到的如下场景:a给b付款10元,a扣了10元,b要加10元。此时c给b2元,但是b的加十元代码约为:
if(b.value.compareAndSet(old, value)){
//try again
// if that fails, rollback and log
AtomicReference
对于AtomicReference 来讲,也许对象会出现,属性丢失的情况,即oldObject == current,但是oldObject.getPropertyA != current.getPropertyA。
这时候,AtomicStampedReference就派上用场了。这也是一个很常用的思路,即加上版本号
3.Lock类 
lock: 在java.util.concurrent包内。共有三个实现:
ReentrantLock
ReentrantReadWriteLock.ReadLock
ReentrantReadWriteLock.WriteLock
主要目的是和synchronized一样, 两者都是为了解决同步问题,处理资源争端而产生的技术。功能类似但有一些区别。
区别如下:
lock更灵活,可以自由定义多把锁的枷锁解锁顺序(synchronized要按照先加的后解顺序)
提供多种加锁方案,lock 阻塞式, trylock 无阻塞式, lockInterruptily 可打断式, 还有trylock的带超时时间版本。
本质上和监视器锁(即synchronized是一样的)
能力越大,责任越大,必须控制好加锁和解锁,否则会导致灾难。
和Condition类的结合。
性能更高,对比如下图:
synchronized和Lock性能对比
ReentrantLock    可重入的意义在于持有锁的线程可以继续持有,并且要释放对等的次数后才真正释放该锁。使用方法是:
1.先new一个实例
static ReentrantLock r=new ReentrantLock();
2.加锁      
r.lock()或r.lockInterruptibly();
此处也是个不同,后者可被打断。当a线程lock后,b线程阻塞,此时如果是lockInterruptibly,那么在调用b.interrupt()之后,b线程退出阻塞,并放弃对资源的争抢,进入catch块。(如果使用后者,必须throw interruptable exception 或catch)    
3.释放锁   
r.unlock()
必须做!何为必须做呢,要放在finally里面。以防止异常跳出了正常流程,导致灾难。这里补充一个小知识点,finally是可以信任的:经过测试,哪怕是发生了OutofMemoryError,finally块中的语句执行也能够得到保证。
ReentrantReadWriteLock
可重入读写锁(读写锁的一个实现) 
 ReentrantReadWriteLock lock = new ReentrantReadWriteLock()
  ReadLock r = lock.readLock();
  WriteLock w = lock.writeLock();
两者都有lock,unlock方法。写写,写读互斥;读读不互斥。可以实现并发读的高效线程安全代码
这里就讨论比较常用的两个:
BlockingQueue
ConcurrentHashMap
BlockingQueue阻塞队列。该类是java.util.concurrent包下的重要类,通过对Queue的学习可以得知,这个queue是单向队列,可以在队列头添加元素和在队尾删除或取出元素。类似于一个管  道,特别适用于先进先出策略的一些应用场景。普通的queue接口主要实现有PriorityQueue(优先队列),有兴趣可以研究
BlockingQueue在队列的基础上添加了多线程协作的功能:
BlockingQueue
除了传统的queue功能(表格左边的两列)之外,还提供了阻塞接口put和take,带超时功能的阻塞接口offer和poll。put会在队列满的时候阻塞,直到有空间时被唤醒;take在队 列空的时候阻塞,直到有东西拿的时候才被唤醒。用于生产者-消费者模型尤其好用,堪称神器。
常见的阻塞队列有:
ArrayListBlockingQueue
LinkedListBlockingQueue
DelayQueue
SynchronousQueue
ConcurrentHashMap高效的线程安全哈希map。请对比hashTable , concurrentHashMap, HashMap
管理类的概念比较泛,用于管理线程,本身不是多线程的,但提供了一些机制来利用上述的工具做一些封装。了解到的值得一提的管理类:ThreadPoolExecutor和 JMX框架下的系统级管理类 ThreadMXBeanThreadPoolExecutor如果不了解这个类,应该了解前面提到的ExecutorService,开一个自己的线程池非常方便:
ExecutorService e = Executors.newCachedThreadPool();
ExecutorService e = Executors.newSingleThreadExecutor();
ExecutorService e = Executors.newFixedThreadPool(3);
// 第一种是可变大小线程池,按照任务数来分配线程,
// 第二种是单线程池,相当于FixedThreadPool(1)
// 第三种是固定大小线程池。
// 然后运行
e.execute(new MyRunnableImpl());
该类内部是通过ThreadPoolExecutor实现的,掌握该类有助于理解线程池的管理,本质上,他们都是ThreadPoolExecutor类的各种实现版本。请参见javadoc:
ThreadPoolExecutor参数解释
翻译一下:
corePoolSize:池内线程初始值与最小值,就算是空闲状态,也会保持该数量线程。
maximumPoolSize:线程最大值,线程的增长始终不会超过该值。
keepAliveTime:当池内线程数高于corePoolSize时,经过多少时间多余的空闲线程才会被回收。回收前处于wait状态
时间单位,可以使用TimeUnit的实例,如TimeUnit.MILLISECONDS 
workQueue:待入任务(Runnable)的等待场所,该参数主要影响调度策略,如公平与否,是否产生饿死(starving)
threadFactory:线程工厂类,有默认实现,如果有自定义的需要则需要自己实现ThreadFactory接口并作为参数传入。
文/知米丶无忌(简书作者)原文链接:http://www.jianshu.com/p/40d4c7aebd66著作权归作者所有,转载请联系作者获得授权,并标注&简书作者&。
阅读(...) 评论()深入理解java线程池—ThreadPoolExecutor - 简书
深入理解java线程池—ThreadPoolExecutor
几句闲扯:首先,我想说java的线程池真的是很绕,以前一直都感觉新建几个线程一直不退出到底是怎么实现的,也就有了后来学习ThreadPoolExecutor源码。学习源码的过程中,最恶心的其实就是几种状态的转换了,这也是ThreadPoolExecutor的核心。花了将近小一周才大致的弄明白ThreadPoolExecutor的机制,遂记录下来。
线程池有多重要#####
线程是一个程序员一定会涉及到的一个概念,但是线程的创建和切换都是代价比较大的。所以,我们有没有一个好的方案能做到线程的复用呢?这就涉及到一个概念——线程池。合理的使用线程池能够带来3个很明显的好处:
1.降低资源消耗:通过重用已经创建的线程来降低线程创建和销毁的消耗
2.提高响应速度:任务到达时不需要等待线程创建就可以立即执行。
3.提高线程的可管理性:线程池可以统一管理、分配、调优和监控。
java多线程池的支持——ThreadPoolExecutor#####
java的线程池支持主要通过ThreadPoolExecutor来实现,我们使用的ExecutorService的各种线程池策略都是基于ThreadPoolExecutor实现的,所以ThreadPoolExecutor十分重要。要弄明白各种线程池策略,必须先弄明白ThreadPoolExecutor。
1. 实现原理#####
首先看一个线程池的流程图:
Paste_Image.png
step1.调用ThreadPoolExecutor的execute提交线程,首先检查CorePool,如果CorePool内的线程小于CorePoolSize,新创建线程执行任务。
step2.如果当前CorePool内的线程大于等于CorePoolSize,那么将线程加入到BlockingQueue。
step3.如果不能加入BlockingQueue,在小于MaxPoolSize的情况下创建线程执行任务。
step4.如果线程数大于等于MaxPoolSize,那么执行拒绝策略。
2.线程池的创建#####
线程池的创建可以通过ThreadPoolExecutor的构造方法实现:
* 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
* @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
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 = corePoolS
this.maximumPoolSize = maximumPoolS
this.workQueue = workQ
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadF
this.handler =
具体解释一下上述参数:
corePoolSize 核心线程池大小
maximumPoolSize 线程池最大容量大小
keepAliveTime 线程池空闲时,线程存活的时间
ThreadFactory 线程工厂
BlockingQueue任务队列
RejectedExecutionHandler 线程拒绝策略
3.线程的提交#####
ThreadPoolExecutor的构造方法如上所示,但是只是做一些参数的初始化,ThreadPoolExecutor被初始化好之后便可以提交线程任务,线程的提交方法主要是execute和submit。这里主要说execute,submit会在后续的博文中分析。
* Executes the given task sometime in the future.
* may execute in a new thread or in an existing pooled thread.
* If the task cannot be submitted for execution, either because this
* executor has been shutdown or because its capacity has been reached,
* the task is handled by the current {@code RejectedExecutionHandler}.
* @param command the task to execute
* @throws RejectedExecutionException at discretion of
{@code RejectedExecutionHandler}, if the task
cannot be accepted for execution
* @throws NullPointerException if {@code command} is null
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
* 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
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.
* 如果当前的线程数小于核心线程池的大小,根据现有的线程作为第一个Worker运行的线程,
* 新建一个Worker,addWorker自动的检查当前线程池的状态和Worker的数量,
* 防止线程池在不能添加线程的状态下添加线程
* 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.
如果线程入队成功,然后还是要进行double-check的,因为线程池在入队之后状态是可能会发生变化的
* 3. If we cannot queue task, then we try to add a new
If it fails, we know we are shut down or saturated
* and so reject the task.
* 如果task不能入队(队列满了),这时候尝试增加一个新线程,如果增加失败那么当前的线程池状态变化了或者线程池已经满了
* 然后拒绝task
int c = ctl.get();
//当前的Worker的数量小于核心线程池大小时,新建一个Worker。
if (workerCountOf(c) & corePoolSize) {
if (addWorker(command, true))
c = ctl.get();
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))//recheck防止线程池状态的突变,如果突变,那么将reject线程,防止workQueue中增加新线程
reject(command);
else if (workerCountOf(recheck) == 0)//上下两个操作都有addWorker的操作,但是如果在workQueue.offer的时候Worker变为0,
//那么将没有Worker执行新的task,所以增加一个Worker.
addWorker(null, false);
//如果workQueue满了,那么这时候可能还没到线程池的maxnum,所以尝试增加一个Worker
else if (!addWorker(command, false))
reject(command);//如果Worker数量到达上限,那么就拒绝此线程
这里需要明确几个概念:
Worker和Task的区别,Worker是当前线程池中的线程,而task虽然是runnable,但是并没有真正执行,只是被Worker调用了run方法,后面会看到这部分的实现。
maximumPoolSize和corePoolSize的区别:这个概念很重要,maximumPoolSize为线程池最大容量,也就是说线程池最多能起多少Worker。corePoolSize是核心线程池的大小,当corePoolSize满了时,同时workQueue full(ArrayBolckQueue是可能满的) 那么此时允许新建Worker去处理workQueue中的Task,但是不能超过maximumPoolSize。超过corePoolSize之外的线程会在空闲超时后终止。
核心方法:addWorker#####
Worker的增加和Task的获取以及终止都是在此方法中实现的,也就是这一个方法里面包含了很多东西。在addWorker方法中提到了Status的概念,Status是线程池的核心概念,这里我们先看一段关于status的注释:
* 首先ctl是一个原子量,同时它里面包含了两个field,一个是workerCount,另一个是runState
* workerCount表示当前有效的线程数,也就是Worker的数量
* runState表示当前线程池的状态
* The main pool control state, ctl, is an atomic integer packing
* two conceptual fields
workerCount, indicating the effective number of threads
indicating whether running, shutting down etc
* 两者是怎么结合的呢?首先workerCount是占据着一个atomic integer的后29位的,而状态占据了前3位
* 所以,workerCount上限是(2^29)-1。
* In order to pack them into one int, we limit workerCount to
* (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2
* billion) otherwise representable. If this is ever an issue in
* the future, the variable can be changed to be an AtomicLong,
* and the shift/mask constants below adjusted. But until the need
* arises, this code is a bit faster and simpler using an int.
* The workerCount is the number of workers that have been
* permitted to start and not permitted to stop.
The value may be
* transiently different from the actual number of live threads,
* for example when a ThreadFactory fails to create a thread when
* asked, and when exiting threads are still performing
* bookkeeping before terminating. The user-visible pool size is
* reported as the current size of the workers set.
* runState是整个线程池的运行生命周期,有如下取值:
1. RUNNING:可以新加线程,同时可以处理queue中的线程。
2. SHUTDOWN:不增加新线程,但是处理queue中的线程。
3.STOP 不增加新线程,同时不处理queue中的线程。
4.TIDYING 所有的线程都终止了(queue中),同时workerCount为0,那么此时进入TIDYING
5.terminated()方法结束,变为TERMINATED
* The runState provides the main lifecyle control, taking on values:
Accept new tasks and process queued tasks
SHUTDOWN: Don't accept new tasks, but process queued tasks
Don't accept new tasks, don't process queued tasks,
and interrupt in-progress tasks
All tasks have terminated, workerCount is zero,
the thread transitioning to state TIDYING
will run the terminated() hook method
TERMINATED: terminated() has completed
* The numerical order among these values matters, to allow
* ordered comparisons. The runState monotonically increases over
* time, but need not hit each state. The transitions are:
* 状态的转化主要是:
* RUNNING -& SHUTDOWN(调用shutdown())
On invocation of shutdown(), perhaps implicitly in finalize()
* (RUNNING or SHUTDOWN) -& STOP(调用shutdownNow())
On invocation of shutdownNow()
* SHUTDOWN -& TIDYING(queue和pool均empty)
When both queue and pool are empty
* STOP -& TIDYING(pool empty,此时queue已经为empty)
When pool is empty
* TIDYING -& TERMINATED(调用terminated())
When the terminated() hook method has completed
* Threads waiting in awaitTermination() will return when the
* state reaches TERMINATED.
* Detecting the transition from SHUTDOWN to TIDYING is less
* straightforward than you'd like because the queue may become
* empty after non-empty and vice versa during SHUTDOWN state, but
* we can only terminate if, after seeing that it is empty, we see
* that workerCount is 0 (which sometimes entails a recheck -- see
下面是状态的代码:
//利用ctl来保证当前线程池的状态和当前的线程的数量。ps:低29位为线程池容量,高3位为线程状态。
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
//设定偏移量
private static final int COUNT_BITS = Integer.SIZE - 3;
//确定最大的容量2^29-1
private static final int CAPACITY
= (1 && COUNT_BITS) - 1;
//几个状态,用Integer的高三位表示
// runState is stored in the high-order bits
private static final int RUNNING
= -1 && COUNT_BITS;
private static final int SHUTDOWN
0 && COUNT_BITS;
private static final int STOP
1 && COUNT_BITS;
private static final int TIDYING
2 && COUNT_BITS;
private static final int TERMINATED =
3 && COUNT_BITS;
//获取线程池状态,取前三位
// Packing and unpacking ctl
private static int runStateOf(int c)
{ return c & ~CAPACITY; }
//获取当前正在工作的worker,主要是取后面29位
private static int workerCountOf(int c)
{ return c & CAPACITY; }
private static int ctlOf(int rs, int wc) { return rs | }
接下来贴上addWorker方法看看:
* Checks if a new worker can be added with respect to current
* pool state and the given bound (either core or maximum). If so,
* the worker count is adjusted accordingly, and, if possible, a
* new worker is created and started running firstTask as its
* first task. This method returns false if the pool is stopped or
* eligible to shut down. It also returns false if the thread
* factory fails to create a thread when asked, which requires a
* backout of workerCount, and a recheck for termination, in case
* the existence of this worker was holding up termination.
* @param firstTask the task the new thread should run first (or
* null if none). Workers are created with an initial first task
* (in method execute()) to bypass queuing when there are fewer
* than corePoolSize threads (in which case we always start one),
* or when the queue is full (in which case we must bypass queue).
* Initially idle threads are usually created via
* prestartCoreThread or to replace other dying workers.
* @param core if true use corePoolSize as bound, else
* maximumPoolSize. (A boolean indicator is used here rather than a
* value to ensure reads of fresh values after checking other pool
* @return true if successful
private boolean addWorker(Runnable firstTask, boolean core) {
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
* rs!=Shutdown || fistTask!=null || workCount.isEmpty
* 如果当前的线程池的状态&SHUTDOWN 那么拒绝Worker的add 如果=SHUTDOWN
* 那么此时不能新加入不为null的Task,如果在WorkCount为empty的时候不能加入任何类型的Worker,
* 如果不为empty可以加入task为null的Worker,增加消费的Worker
if (rs &= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
for (;;) {
int wc = workerCountOf(c);
if (wc &= CAPACITY ||
wc &= (core ? corePoolSize : maximumPoolSize))
if (compareAndIncrementWorkerCount(c))
c = ctl.get();
// Re-read ctl
if (runStateOf(c) != rs)
// else CAS failed due to workerC retry inner loop
Worker w = new Worker(firstTask);
Thread t = w.
final ReentrantLock mainLock = this.mainL
mainLock.lock();
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int c = ctl.get();
int rs = runStateOf(c);
* rs!=SHUTDOWN ||firstTask!=null
* 同样检测当rs&SHUTDOWN时直接拒绝减小Wc,同时Terminate,如果为SHUTDOWN同时firstTask不为null的时候也要Terminate
if (t == null ||
(rs &= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null))) {
decrementWorkerCount();
tryTerminate();
workers.add(w);
int s = workers.size();
if (s & largestPoolSize)
largestPoolSize =
} finally {
mainLock.unlock();
t.start();
// It is possible (but unlikely) for a thread to have been
// added to workers, but not yet started, during transition to
// STOP, which could result in a rare missed interrupt,
// because Thread.interrupt is not guaranteed to have any effect
// on a non-yet-started Thread (see Thread#interrupt).
//Stop或线程Interrupt的时候要中止所有的运行的Worker
if (runStateOf(ctl.get()) == STOP && ! t.isInterrupted())
t.interrupt();
addWorker中首先进行了一次线程池状态的检测:
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
//判断当前线程池的状态是不是已经shutdown,如果shutdown了拒绝线程加入
//(rs!=SHUTDOWN || first!=null || workQueue.isEmpty())
//如果rs不为SHUTDOWN,此时状态是STOP、TIDYING或TERMINATED,所以此时要拒绝请求
//如果此时状态为SHUTDOWN,而传入一个不为null的线程,那么需要拒绝
//如果状态为SHUTDOWN,同时队列中已经没任务了,那么拒绝掉
if (rs &= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
其实是比较难懂的,主要在线程池状态判断条件这里:
如果是runing,那么跳过if。
如果rs&=SHUTDOWN,同时不等于SHUTDOWN,即为SHUTDOWN以上的状态,那么不接受新线程。
如果rs&=SHUTDOWN,同时等于SHUTDOWN,同时first!=null,那么拒绝新线程,如果first==null,那么可能是新增加线程消耗Queue中的线程。但是同时还要检测workQueue是否isEmpty(),如果为Empty,那么队列已空,不需要增加消耗线程,如果队列没有空那么运行增加first=null的Worker。
从这里是可以看出一些策略的
首先,在rs&SHUTDOWN时,拒绝一切线程的增加,因为STOP是会终止所有的线程,同时移除Queue中所有的待执行的线程的,所以也不需要增加first=null的Worker了
其次,在SHUTDOWN状态时,是不能增加first!=null的Worker的,同时即使first=null,但是此时Queue为Empty也是不允许增加Worker的,SHUTDOWN下增加的Worker主要用于消耗Queue中的任务。
SHUTDOWN状态时,是不允许向workQueue中增加线程的,isRunning(c) && workQueue.offer(command) 每次在offer之前都要做状态检测,也就是线程池状态变为&=SHUTDOWN时不允许新线程进入线程池了。
for (;;) {
int wc = workerCountOf(c);
//如果当前的数量超过了CAPACITY,或者超过了corePoolSize和maximumPoolSize(试core而定)
if (wc &= CAPACITY ||
wc &= (core ? corePoolSize : maximumPoolSize))
//CAS尝试增加线程数,如果失败,证明有竞争,那么重新到retry。
if (compareAndIncrementWorkerCount(c))
c = ctl.get();
// Re-read ctl
//判断当前线程池的运行状态
if (runStateOf(c) != rs)
// else CAS failed due to workerC retry inner loop
这段代码做了一个兼容,主要是没有到corePoolSize 或maximumPoolSize上限时,那么允许添加线程,CAS增加Worker的数量后,跳出循环。
接下来实例化Worker,实例化Worker其实是很关键的,后面会说。
因为workers是HashSet线程不安全的,那么此时需要加锁,所以mainLock.lock(); 之后重新检查线程池的状态,如果状态不正确,那么减小Worker的数量,为什么tryTerminate()目前不大清楚。如果状态正常,那么添加Worker到workers。最后:
if (runStateOf(ctl.get()) == STOP && ! t.isInterrupted())
t.interrupt();
注释说的很清楚,为了能及时的中断此Worker,因为线程存在未Start的情况,此时是不能响应中断的,如果此时status变为STOP,则不能中断线程。此处用作中断线程之用。
接下来我们看Worker的方法:
* Creates with given first task and thread from ThreadFactory.
* @param firstTask the first task (null if none)
Worker(Runnable firstTask) {
this.firstTask = firstT
this.thread = getThreadFactory().newThread(this);
这里可以看出Worker是对firstTask的包装,并且Worker本身就是Runnable的,看上去真心很流氓的感觉~~~
通过ThreadFactory为Worker自己构建一个线程。
因为Worker是Runnable类型的,所以是有run方法的,上面也看到了会调用t.start() 其实就是执行了run方法:
/** Delegates main run loop to outer runWorker
public void run() {
runWorker(this);
调用了runWorker:
* Main worker run loop.
Repeatedly gets tasks from queue and
* executes them, while coping with a number of issues:
* 1 Worker可能还是执行一个初始化的task——firstTask。
但是有时也不需要这个初始化的task(可以为null),只要pool在运行,就会
通过getTask从队列中获取Task,如果返回null,那么worker退出。
另一种就是external抛出异常导致worker退出。
* 1. We may start out with an initial task, in which case we
* don't need to get the first one. Otherwise, as long as pool is
* running, we get tasks from getTask. If it returns null then the
* worker exits due to changed pool state or configuration
* parameters.
Other exits result from exception throws in
* external code, in which case completedAbruptly holds, which
* usually leads processWorkerExit to replace this thread.
* 2 在运行任何task之前,都需要对worker加锁来防止other pool中断worker。
clearInterruptsForTaskRun保证除了线程池stop,那么现场都没有中断标志
* 2. Before running any task, the lock is acquired to prevent
* other pool interrupts while the task is executing, and
* clearInterruptsForTaskRun called to ensure that unless pool is
* stopping, this thread does not have its interrupt set.
* 3. Each task run is preceded by a call to beforeExecute, which
* might throw an exception, in which case we cause thread to die
* (breaking loop with completedAbruptly true) without processing
* the task.
* 4. Assuming beforeExecute completes normally, we run the task,
* gathering any of its thrown exceptions to send to
* afterExecute. We separately handle RuntimeException, Error
* (both of which the specs guarantee that we trap) and arbitrary
* Throwables.
Because we cannot rethrow Throwables within
* Runnable.run, we wrap them within Errors on the way out (to the
* thread's UncaughtExceptionHandler).
Any thrown exception also
* conservatively causes thread to die.
* 5. After task.run completes, we call afterExecute, which may
* also throw an exception, which will also cause thread to
* die. According to JLS Sec 14.20, this exception is the one that
* will be in effect even if task.run throws.
* The net effect of the exception mechanics is that afterExecute
* and the thread's UncaughtExceptionHandler have as accurate
* information as we can provide about any problems encountered by
* user code.
* @param w the worker
final void runWorker(Worker w) {
Runnable task = w.firstT
w.firstTask =
//标识线程是不是异常终止的
boolean completedAbruptly =
//task不为null情况是初始化worker时,如果task为null,则去队列中取线程---&getTask()
while (task != null || (task = getTask()) != null) {
//获取woker的锁,防止线程被其他线程中断
clearInterruptsForTaskRun();//清楚所有中断标记
beforeExecute(w.thread, task);//线程开始执行之前执行此方法,可以实现Worker未执行退出,本类中未实现
Throwable thrown =
task.run();
} catch (RuntimeException x) {
} catch (Error x) {
} catch (Throwable x) {
thrown = throw new Error(x);
} finally {
afterExecute(task, thrown);//线程执行后执行,可以实现标识Worker异常中断的功能,本类中未实现
} finally {
task =//运行过的task标null
w.completedTasks++;
w.unlock();
completedAbruptly =
} finally {
//处理worker退出的逻辑
processWorkerExit(w, completedAbruptly);
从上面代码可以看出,execute的Task是被“包装 ”了一层,线程启动时是内部调用了Task的run方法。
接下来所有的核心集中在getTask()方法上:
* Performs blocking or timed wait for a task, depending on
* current configuration settings, or returns null if this worker
* must exit because of any of:
* 1. There are more than maximumPoolSize workers (due to
a call to setMaximumPoolSize).
* 2. The pool is stopped.
* 3. The pool is shutdown and the queue is empty.
* 4. This worker timed out waiting for a task, and timed-out
workers are subject to termination (that is,
{@code allowCoreThreadTimeOut || workerCount & corePoolSize})
both before and after the timed wait.
* @return task, or null if the worker must exit, in which case
workerCount is decremented
队列中获取线程
private Runnable getTask() {
boolean timedOut = // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
//当前状态为&stop时,不处理workQueue中的任务,同时减小worker的数量所以返回null,如果为shutdown 同时workQueue已经empty了,同样减小worker数量并返回null
if (rs &= SHUTDOWN && (rs &= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
// Are workers subject to culling?
for (;;) {
int wc = workerCountOf(c);
timed = allowCoreThreadTimeOut || wc & corePoolS
if (wc &= maximumPoolSize && ! (timedOut && timed))
if (compareAndDecrementWorkerCount(c))
c = ctl.get();
// Re-read ctl
if (runStateOf(c) != rs)
// else CAS failed due to workerC retry inner loop
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
timedOut =
} catch (InterruptedException retry) {
timedOut =
这段代码十分关键,首先看几个局部变量:
boolean timedOut =
主要是判断后面的poll是否要超时
主要是标识着当前Worker超时是否要退出。wc & corePoolSize时需要减小空闲的Worker数,那么timed为true,但是wc &= corePoolSize时,不能减小核心线程数timed为false。
timedOut初始为false,如果timed为true那么使用poll取线程。如果正常返回,那么返回取到的task。如果超时,证明worker空闲,同时worker超过了corePoolSize,需要删除。返回r=null。则 timedOut = true。此时循环到wc &= maximumPoolSize && ! (timedOut && timed)时,减小worker数,并返回null,导致worker退出。如果线程数&= corePoolSize,那么此时调用 workQueue.take(),没有线程获取到时将一直阻塞,知道获取到线程或者中断,关于中断后面Shutdown的时候会说。
至此线程执行过程就分析完了~~~~
关于终止线程池#####
我个人认为,如果想了解明白线程池,那么就一定要理解好各个状态之间的转换,想理解转换,线程池的终止机制是很好的一个途径。对于关闭线程池主要有两个方法shutdown()和shutdownNow():
首先从shutdown()方法开始:
* Initiates an orderly shutdown in which previously submitted
* tasks are executed, but no new tasks will be accepted.
* Invocation has no additional effect if already shut down.
* &p&This method does not wait for previously submitted tasks to
* complete execution.
Use {@link #awaitTermination awaitTermination}
* to do that.
* @throws SecurityException {@inheritDoc}
public void shutdown() {
final ReentrantLock mainLock = this.mainL
mainLock.lock();
//判断是否可以操作目标线程
checkShutdownAccess();
//设置线程池状态为SHUTDOWN,此处之后,线程池中不会增加新Task
advanceRunState(SHUTDOWN);
//中断所有的空闲线程
interruptIdleWorkers();
onShutdown(); // hook for ScheduledThreadPoolExecutor
} finally {
mainLock.unlock();
//转到Terminate
tryTerminate();
shutdown做了几件事:
1. 检查是否能操作目标线程
2. 将线程池状态转为SHUTDOWN
3. 中断所有空闲线程
这里就引发了一个问题,什么是空闲线程?
这需要接着看看interruptIdleWorkers是怎么回事。
private void interruptIdleWorkers(boolean onlyOne) {
final ReentrantLock mainLock = this.mainL
mainLock.lock();
//这里的意图很简单,遍历workers 对所有worker做中断处理。
// w.tryLock()对Worker加锁,这保证了正在运行执行Task的Worker不会被中断,那么能中断哪些线程呢?
for (Worker w : workers) {
Thread t = w.
if (!t.isInterrupted() && w.tryLock()) {
t.interrupt();
} catch (SecurityException ignore) {
} finally {
w.unlock();
if (onlyOne)
} finally {
mainLock.unlock();
这里主要是为了中断worker,但是中断之前需要先获取锁,这就意味着正在运行的Worker不能中断。但是上面的代码有w.tryLock(),那么获取不到锁就不会中断,shutdown的Interrupt只是对所有的空闲Worker(正在从workQueue中取Task,此时Worker没有加锁)发送中断信号。
while (task != null || (task = getTask()) != null) {
//获取woker的锁,防止线程被其他线程中断
clearInterruptsForTaskRun();//清楚所有中断标记
beforeExecute(w.thread, task);//线程开始执行之前执行此方法,可以实现Worker未执行退出,本类中未实现
Throwable thrown =
task.run();
} catch (RuntimeException x) {
} catch (Error x) {
} catch (Throwable x) {
thrown = throw new Error(x);
} finally {
afterExecute(task, thrown);//线程执行后执行,可以实现标识Worker异常中断的功能,本类中未实现
} finally {
task =//运行过的task标null
w.completedTasks++;
w.unlock();
在runWorker中,每一个Worker getTask成功之后都要获取Worker的锁之后运行,也就是说运行中的Worker不会中断。因为核心线程一般在空闲的时候会一直阻塞在获取Task上,也只有中断才可能导致其退出。这些阻塞着的Worker就是空闲的线程(当然,非核心线程,并且阻塞的也是空闲线程)。在getTask方法中:
private Runnable getTask() {
boolean timedOut = // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
//当前状态为&stop时,不处理workQueue中的任务,同时减小worker的数量所以返回null,如果为shutdown 同时workQueue已经empty了,同样减小worker数量并返回null
if (rs &= SHUTDOWN && (rs &= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
// Are workers subject to culling?
for (;;) {
//allowCoreThreadTimeOu是判断CoreThread是否会超时的,true为会超时,false不会超时。默认为false
int wc = workerCountOf(c);
timed = allowCoreThreadTimeOut || wc & corePoolS
if (wc &= maximumPoolSize && ! (timedOut && timed))
if (compareAndDecrementWorkerCount(c))
c = ctl.get();
// Re-read ctl
if (runStateOf(c) != rs)
// else CAS failed due to workerC retry inner loop
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
timedOut =
} catch (InterruptedException retry) {
timedOut =
会有两阶段的Worker:
刚进入getTask(),还没进行状态判断。
block在poll或者take上的Worker。
当调用ShutDown方法时,首先设置了线程池的状态为ShutDown,此时1阶段的worker进入到状态判断时会返回null,此时Worker退出。
因为getTask的时候是不加锁的,所以在shutdown时可以调用worker.Interrupt.此时会中断退出,Loop到状态判断时,同时workQueue为empty。那么抛出中断异常,导致重新Loop,在检测线程池状态时,Worker退出。如果workQueue不为null就不会退出,此处有些疑问,因为没有看见中断标志位清除的逻辑,那么这里就会不停的循环直到workQueue为Empty退出。
这里也能看出来SHUTDOWN只是清除一些空闲Worker,并且拒绝新Task加入,对于workQueue中的线程还是继续处理的。
对于shutdown中获取mainLock而addWorker中也做了mainLock的获取,这么做主要是因为Works是HashSet类型的,是线程不安全的,我们也看到在addWorker后面也是对线程池状态做了判断,将Worker添加和中断逻辑分离开。
接下来做了tryTerminate()操作,这操作是进行了后面状态的转换,在shutdownNow后面说。
接下来看看shutdownNow:
* Attempts to stop all actively executing tasks, halts the
* processing of waiting tasks, and returns a list of the tasks
* that were awaiting execution. These tasks are drained (removed)
* from the task queue upon return from this method.
* &p&This method does not wait for actively executing tasks to
* terminate.
Use {@link #awaitTermination awaitTermination} to
* do that.
* &p&There are no guarantees beyond best-effort attempts to stop
* processing actively executing tasks.
This implementation
* cancels tasks via {@link Thread#interrupt}, so any task that
* fails to respond to interrupts may never terminate.
* @throws SecurityException {@inheritDoc}
public List&Runnable& shutdownNow() {
List&Runnable&
final ReentrantLock mainLock = this.mainL
mainLock.lock();
checkShutdownAccess();
advanceRunState(STOP);
interruptWorkers();
tasks = drainQueue();
} finally {
mainLock.unlock();
tryTerminate();
shutdownNow和shutdown代码类似,但是实现却很不相同。首先是设置线程池状态为STOP,前面的代码我们可以看到,是对SHUTDOWN有一些额外的判断逻辑,但是对于&=STOP,基本都是reject,STOP也是比SHUTDOWN更加严格的一种状态。此时不会有新Worker加入,所有刚执行完一个线程后去GetTask的Worker都会退出。
之后调用interruptWorkers:
* Interrupts all threads, even if active. Ignores SecurityExceptions
* (in which case some threads may remain uninterrupted).
private void interruptWorkers() {
final ReentrantLock mainLock = this.mainL
mainLock.lock();
for (Worker w : workers) {
w.thread.interrupt();
} catch (SecurityException ignore) {
} finally {
mainLock.unlock();
这里可以看出来,此方法目的是中断所有的Worker,而不是像shutdown中那样只中断空闲线程。这样体现了STOP的特点,中断所有线程,同时workQueue中的Task也不会执行了。所以接下来drainQueue:
* Drains the task queue into a new list, normally using
* drainTo. But if the queue is a DelayQueue or any other kind of
* queue for which poll or drainTo may fail to remove some
* elements, it deletes them one by one.
private List&Runnable& drainQueue() {
BlockingQueue&Runnable& q = workQ
List&Runnable& taskList = new ArrayList&Runnable&();
q.drainTo(taskList);
if (!q.isEmpty()) {
for (Runnable r : q.toArray(new Runnable[0])) {
if (q.remove(r))
taskList.add(r);
return taskL
获取所有没有执行的Task,并且返回。
这也体现了STOP的特点:
拒绝所有新Task的加入,同时中断所有线程,WorkerQueue中没有执行的线程全部抛弃。所以此时Pool是空的,WorkerQueue也是空的。
这之后就是进行到TIDYING和TERMINATED的转化了:
* Transitions to TERMINATED state if either (SHUTDOWN and pool
* and queue empty) or (STOP and pool empty).
If otherwise
* eligible to terminate but workerCount is nonzero, interrupts an
* idle worker to ensure that shutdown signals propagate. This
* method must be called following any action that might make
* termination possible -- reducing worker count or removing tasks
* from the queue during shutdown. The method is non-private to
* allow access from ScheduledThreadPoolExecutor.
final void tryTerminate() {
for (;;) {
int c = ctl.get();
if (isRunning(c) ||
runStateAtLeast(c, TIDYING) ||
(runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty()))
if (workerCountOf(c) != 0) { // Eligible to terminate
interruptIdleWorkers(ONLY_ONE);
final ReentrantLock mainLock = this.mainL
mainLock.lock();
if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) {
terminated();
} finally {
ctl.set(ctlOf(TERMINATED, 0));
termination.signalAll();
} finally {
mainLock.unlock();
// else retry on failed CAS
上面的代码其实很有意思有几种状态是不能转化到TIDYING的:
RUNNING状态
TIDYING或TERMINATED
SHUTDOWN状态,但是workQueue不为空
也说明了两点:
1. SHUTDOWN想转化为TIDYING,需要workQueue为空,同时workerCount为0。
2. STOP转化为TIDYING,需要workerCount为0
如果满足上面的条件(一般一定时间后都会满足的),那么CAS成TIDYING,TIDYING也只是个过度状态,最终会转化为TERMINATED。
至此,ThreadPoolExecutor一些核心思想就介绍完了,想分析清楚实在是不容易,对于ThreadPoolExecutor我还是有些不懂地方,以上只是我对源码的片面的见解,如果有不正确之处,希望大神能不吝赐教。同时也希望给正在研究ThreadPoolExecutor的童鞋提供一点帮助。
勿忘初心,方得始终。晚安~~
帝都小码农,酷爱编程,一、二、三线互联网公司都混过,热爱读书和收藏书。比较关注后台以及大数据处理相关的技术。
博客链接:http://www.ideabuffer.cn//深入理解Java线程池:ThreadPoolExecutor/ 线程池介绍 在web开发中,服务器需要接受并处理请求,所以会为一个请求来分配一个线程来进行处理。如果每次请求都新创建一个线程的话...
前言 JDK中为我们提供了一个并发线程框架,它是的我们可以在有异步任务或大量并发任务需要执行时可以使用它提供的线程池,大大方便了我们使用线程,同时将我们从创建、管理线程的繁琐任务中解放出来,能够更加快速的实现业务、功能。合理的使用线程池可以为我们带来三个好处: 降低资源消耗...
原文出处http://cmsblogs.com/ 『chenssy』 作为Executor框架中最核心的类,ThreadPoolExecutor代表着鼎鼎大名的线程池,它给了我们足够的理由来弄清楚它。 下面我们就通过源码来一步一步弄清楚它。 内部状态 线程有五种状态:新建,...
线程池常见实现 线程池一般包含三个主要部分: 调度器: 决定由哪个线程来执行任务, 执行任务所能够的最大耗时等 线程队列: 存放并管理着一系列线程, 这些线程都处于阻塞状态或休眠状态 任务队列: 存放着用户提交的需要被执行的任务. 一般任务的执行 FIFO 的, 即先提交的...
Java有两个线程池类:ThreadPoolExecutor和ScheduledThreadPoolExecutor,且均继承于ExecutorService。Java API提供了Executors工厂类来帮助创建各种线程池。Java线程池ExecutorService继...
食品安全无小事,除了老百姓日常接触到的社会餐饮,在飞机上,食品安全更为重要。在万米高空,航空餐究竟是在哪制作的?又是如何保障食品安全卫生的? 厨房在地面 配餐厅在万米高空 记者从扬州泰州国际机场获悉,近日在2016年度国航配餐公司工作会议上,国内外120多家配餐公司中,扬州...
天哥抱着枕头死皮赖脸要和我腻味一晚上,说今天特别特别想躺妈妈怀抱滴赶脚。 俺说:你可是大孩子了罗,确定要撒娇吗? 天哥曰:你呀好好珍惜吧、这样的好日子不多了滴。我现在初一、偶尔还会想撒撒娇,等我初二了你就没有机会了。 俺瞬间无语鸟~确实如此、俺们做父母和孩子之间这样亲密时光...
早晨起床,第一个想到的就是你,我想,这就是爱吧~ 想在你身旁苏醒,想醒了就听到你说早安,想起床就和你互相腻歪互相告白——“我爱你” 2013年,高二上期,和你分到一个班,那时的你就想妇联主席,对每个女生都特别好,和你一个班的交道最多就是发作业、试卷,而那时的我,最讨厌你这种...
原始网页:R markdown 概述 R markdown是R语言运行环境RStudio所使用的扩展的markdown标签语言,能够方便的利用R语言生成web格式的报告。它包括核心的Markdown语法,并能将其中插入的R代码区块的运行结果显示在最终文档里。R Markdo...
有一夜疲惫的梦 辗转的都是前世的痛 夏日的晨光迟迟 不能将我轻轻唤醒 鸟语在耳畔嘶鸣 流光不忍揾去泪痕 跫音点点入心魂 共谁知那片深情 香花又开过了一春 雨露朦胧了曾经 那个清水模样的你 是如此这般动人 有一世迷惘的情 缠绵的都是难言的恨 秋月的夜光泠泠 不能消解心中怨愤 ...

我要回帖

更多关于 php 多线程 的文章

 

随机推荐