ThreadPoolExecutor
ThreadPoolExecutor是线程池真正的实现,一共有四种构造方式
分别是
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
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.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
构造方法参数说明
- corePoolSize
核心线程数,默认情况下核心线程会一直存活,即使处于闲置状态也不会受存keepAliveTime限制。除非将allowCoreThreadTimeOut设置为true。
- maximumPoolSize
线程池所能容纳的最大线程数。超过这个数的线程将被阻塞。当任务队列为没有设置大小的LinkedBlockingDeque时,这个值无效。
- keepAliveTime
非核心线程的闲置超时时间,超过这个时间就会被回收。
- unit
指定keepAliveTime的单位,如TimeUnit.SECONDS。当将allowCoreThreadTimeOut设置为true时对corePoolSize生效。
- workQueue
线程池中的任务队列.
常用的有三种队列,SynchronousQueue,LinkedBlockingDeque,ArrayBlockingQueue。
- threadFactory
线程工厂,提供创建新线程的功能。ThreadFactory是一个接口,只有一个方法
public interface ThreadFactory {
Thread newThread(Runnable r);
}
- RejectedExecutionHandler
RejectedExecutionHandler
也是一个接口,只有一个方法
public interface RejectedExecutionHandler {
void rejectedExecution(Runnable var1, ThreadPoolExecutor var2);
}
下面举几个不同情形的例子
情形1、当池中正在运行的线程数(包括空闲线程)小于corePoolSize时,新建线程执行任务。
通俗的说,就是核心线程池还没满,那就尽情的创建线程吧
package threadpool;
import java.security.AccessController;
import java.util.concurrent.*;
/**
* @author ArithmeticJia
* 当池中正在运行的线程数(包括空闲线程)小于corePoolSize时,新建线程执行任务。
* 当执行任务1的线程(thread-1)执行完成之后,任务2并没有去复用thread-1而是新建线程(thread-2)去执行任务。
*/
public class FirstThreadPool {
public static void main(String[] args){
ThreadFactory namedThreadFactory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return null;
}
};
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,10,5, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE));
// 任务1
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("-------------helloworld_001---------------" + Thread.currentThread().getName());
}
});
try {
//主线程睡2秒
Thread.sleep(2*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 任务2
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("-------------helloworld_002---------------" + Thread.currentThread().getName());
}
});
// shutdown就是不再接受新的任务,然后等待线程池全部执行完毕
threadPoolExecutor.shutdown();
// 若关闭后所有任务都已完成,则返回true。
// 注意除非首先调用shutdown或shutdownNow,否则isTerminated永不为true。
// 返回:若关闭后所有任务都已完成,则返回true
// 等待线程池返回结束标志,如果为true,表示全部结束,退出while等待循环
while (!threadPoolExecutor.isTerminated()) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("\n结束了!");
}
}
看下结果打印
-------------helloworld_001---------------pool-1-thread-1
-------------helloworld_002---------------pool-1-thread-2
结束了!
Process finished with exit code 0
当执行任务1的线程(thread-1)执行完成之后,任务2并没有去复用thread-1而是新建线程(thread-2)去执行任务
情形2、当池中正在运行的线程数大于等于corePoolSize时,新插入的任务进入workQueue排队(如果workQueue长度允许),等待空闲线程来执行
简单说,就是核心线程池满了,进入队列,如果此时队列没满的话,等到有线程空闲了,才能执行
package threadpool;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author ArithmeticJia
* 当池中正在运行的线程数大于等于corePoolSize时,新插入的任务进入workQueue排队(如果workQueue长度允许),等待空闲线程来执行
* 任务3会等待任务1执行完之后,有了空闲线程,才会执行。并没有新建线程执行任务3,这时maximumPoolSize=3这个参数不起作用。
*/
public class SecondThreadPool {
public static void main(String[] args){
ThreadFactory namedThreadFactory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return null;
}
};
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,10,5, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE));
// 任务1
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3 * 1000);
System.out.println("-------------helloworld_001---------------" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 任务2
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5 * 1000);
System.out.println("-------------helloworld_002---------------" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 任务3
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("-------------helloworld_003---------------" + Thread.currentThread().getName());
}
});
// shutdown就是不再接受新的任务,然后等待线程池全部执行完毕
threadPoolExecutor.shutdown();
// 若关闭后所有任务都已完成,则返回true。
// 注意除非首先调用shutdown或shutdownNow,否则isTerminated永不为true。
// 返回:若关闭后所有任务都已完成,则返回true
// 等待线程池返回结束标志,如果为true,表示全部结束,退出while等待循环
while (!threadPoolExecutor.isTerminated()) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("\n结束了!");
}
}
-------------helloworld_001---------------pool-1-thread-1
-------------helloworld_003---------------pool-1-thread-1
-------------helloworld_002---------------pool-1-thread-2
结束了!
Process finished with exit code 0
情形3、当队列里的任务数达到上限,并且池中正在运行的线程数小于maximumPoolSize,对于新加入的任务,新建线程。
就是核心线程池满了,队列也满了,但是线程数还没达到最大线程池的数量,此时可以直接创建线程,后来者居上
package threadpool;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author ArithmeticJia
* 当队列里的任务数达到上限,并且池中正在运行的线程数小于maximumPoolSize,对于新加入的任务,新建线程。
* 当任务4进入队列时发现队列的长度已经到了上限,所以无法进入队列排队,而此时正在运行的线程数(2)小于maximumPoolSize所以新建线程执行该任务。
*/
public class ThirdThreadPool {
public static void main(String[] args){
ThreadFactory namedThreadFactory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return null;
}
};
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,3,5, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(1));
// 任务1
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3 * 1000);
System.out.println("-------------helloworld_001---------------" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 任务2
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep( 5 * 1000);
System.out.println("-------------helloworld_002---------------" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 任务3
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("-------------helloworld_003---------------" + Thread.currentThread().getName());
}
});
// 任务4
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("-------------helloworld_004---------------" + Thread.currentThread().getName());
}
});
// shutdown就是不再接受新的任务,然后等待线程池全部执行完毕
threadPoolExecutor.shutdown();
// 若关闭后所有任务都已完成,则返回true。
// 注意除非首先调用shutdown或shutdownNow,否则isTerminated永不为true。
// 返回:若关闭后所有任务都已完成,则返回true
// 等待线程池返回结束标志,如果为true,表示全部结束,退出while等待循环
while (!threadPoolExecutor.isTerminated()) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("\n结束了!");
}
}
当任务4进入队列时发现队列的长度已经到了上限,所以无法进入队列排队,而此时正在运行的线程数(2)小于maximumPoolSize所以新建线程执行该任务,任务4快速执行完成后,线程3空闲,然后去执行队列里的任务3,此时,线程1、2正在全力执行任务1、2
-------------helloworld_004---------------pool-1-thread-3
-------------helloworld_003---------------pool-1-thread-3
-------------helloworld_001---------------pool-1-thread-1
-------------helloworld_002---------------pool-1-thread-2
结束了!
Process finished with exit code 0
情形4、当队列里的任务数达到上限,并且池中正在运行的线程数等于maximumPoolSize,对于新加入的任务,执行拒绝策略(线程池默认的拒绝策略是抛异常)。
package threadpool;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author ArithmeticJia
* 当队列里的任务数达到上限,并且池中正在运行的线程数等于maximumPoolSize,对于新加入的任务,执行拒绝策略(线程池默认的拒绝策略是抛异常)。
* 当任务5加入时,队列达到上限,池内运行的线程数达到最大,故执行默认的拒绝策略,抛异常。
*/
public class FourthThreadPool {
public static void main(String[] args){
ThreadFactory namedThreadFactory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return null;
}
};
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,3,5, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(1));
// 任务1
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3 * 1000);
System.out.println("-------------helloworld_001---------------" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 任务2
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep( 5 * 1000);
System.out.println("-------------helloworld_002---------------" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 任务3
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("-------------helloworld_003---------------" + Thread.currentThread().getName());
}
});
// 任务4
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2 * 1000);
System.out.println("-------------helloworld_004---------------" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 任务5
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("-------------helloworld_005---------------" + Thread.currentThread().getName());
}
});
// shutdown就是不再接受新的任务,然后等待线程池全部执行完毕
threadPoolExecutor.shutdown();
// 若关闭后所有任务都已完成,则返回true。
// 注意除非首先调用shutdown或shutdownNow,否则isTerminated永不为true。
// 返回:若关闭后所有任务都已完成,则返回true
// 等待线程池返回结束标志,如果为true,表示全部结束,退出while等待循环
while (!threadPoolExecutor.isTerminated()) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("\n结束了!");
}
}
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task threadpool.FourthThreadPool$6@5e481248 rejected from java.util.concurrent.ThreadPoolExecutor@66d3c617[Running, pool size = 3, active threads = 3, queued tasks = 1, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
at threadpool.FourthThreadPool.main(FourthThreadPool.java:72)
-------------helloworld_004---------------pool-1-thread-3
-------------helloworld_003---------------pool-1-thread-3
-------------helloworld_001---------------pool-1-thread-1
-------------helloworld_002---------------pool-1-thread-2