目录
使用线程池的好处:
-
降低资源消耗:通过重复利用已创建的线程降低线程创建和销毁造成的消耗。(防止频繁的上下文切换)
-
提高响应速度:当任务到达时,任务可以不需要等到线程创建就能立即执行。
-
提高线程的可管理性:线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。
ThreadPoolExecutor
JDK为我们提供的线程池实现。
1)线程池的状态
ThreadPoolExecutor 使用 int 的高 3 位来表示线程池状态,低 29 位表示线程数量。
下面为其线程状态变化:
状态名 | 高3位 | 接收新任务 | 处理阻塞队列任务 | 说明 |
---|---|---|---|---|
RUNNING | 111 | Y | Y | |
SHUTDOWN | 000 | N | Y | 不会接收新任务,但会处理阻塞队列剩余 任务 |
STOP | 001 | N | N | 会中断正在执行的任务,并抛弃阻塞队列 任务 |
TIDYING | 010 | 任务全执行完毕,活动线程为 0 即将进入 终结 | ||
TERMINATED | 011 | 终结状态 |
线程池状态和线程池中线程的数量由一个原子整型ctl来共同表示。
而使用一个数(不用两个int值)来表示两个值的主要原因是:可以通过一次CAS同时更改两个属性的值
// c 为旧值, ctlOf 返回结果为新值
ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))));
// rs 为高 3 位代表线程池状态, wc 为低 29 位代表线程个数,ctl 是合并它们
private static int ctlOf(int rs, int wc) { return rs | wc; }
2)构造方法
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
参数涵义:
-
corePoolSize
:核心线程数目 -
maximunPoolSize
:最大线程数目(核心线程数+救急线程数) -
keepAliveTime
:救急线程空闲时的最大生存时间 -
unit
:针对救急线程的时间单位 -
workQueue
:阻塞队列;(有界阻塞队列 ArrayBlockingQueue;无界阻塞队列 LinkedBlockingQueue) -
threadFactory
:线程工厂-可以为线程创建时起名字 -
handler
:拒绝策略(它是在救急线程也满运行的时候才会触发)
工作方式:
①线程池刚开始没有线程的,当有任务提交给线程池后,线程池就会创建一个新线程来执行任务;
②当线程数达到核心线程数的数目后,新提交的任务会放入阻塞队列中
③如果阻塞队列(有界队列)也满了之后,再有新任务提交,会创建救急线程来执行这个任务;
④但是当救急线程也满了之后,再来提交的任务就会触发拒绝策略
⑤核心线程核救急线程会一块把任务执行完毕,当救急线程空闲时间超过一段时间后,它就会被移除!
JDK线程池的拒绝策略:
四种实现:
①AbortPolicy
:让调用者抛出RejectedExecutionException 异常,这是默认策略
②CallerRunsPolicy
:让调用者运行任务
③DiscardPolicy
:放弃本次任务
④DiscardOldestPolicy
:放弃队列中最早的任务,本任务取而代之
其它一些框架的实现:
①Dubbo 的实现:在抛出 RejectedExecutionException 异常之前会记录日志,并 dump 线程栈信息,方便定位问题
②Netty 的实现:创建一个新线程来执行任务(不是特别好,没法限制线程数目了)
③ActiveMQ 的实现:带超时等待(60s)尝试放入队列
④PinPoint 的实现:它使用了一个拒绝策略链,会逐一尝试策略链中每种拒绝策
除此之外,JDK Exceutors类提供了众多工厂方法来创建各种用途的线程池:
3)各种用途的线程池
①newFixedThreadPool
创建一个固定大小的线程池;
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
特点:
-
核心线程数 == 最大线程数(没有救急线程被创建),因此也无需超时时间
-
阻塞队列是无界的(LinkedBlockingQueue),可以放任意数量的任务
使用场景:适用于任务量已知,相对耗时的任务
运用方法:
// 创建大小为 2 的固定线程池, 自定义线程名称
ExecutorService executorService = Executors.newFixedThreadPool(2, new ThreadFactory() {
private AtomicInteger atomicInteger = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "my_thread_" + atomicInteger.getAndIncrement());
}
});
// 开 3 个线程, 线程池大小为 2 , 第三个线程执行时, 如果前两个线程任务没执行完, 会加入任务队列.
executorService.execute(() -> {
log.debug("1");
});
executorService.execute(() -> {
log.debug("2");
});
executorService.execute(() -> {
log.debug("3");
});
②newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
特点:
①核心线程数是 0, 最大线程数是 Integer.MAX_VALUE,救急线程的空闲生存时间是 60s,意味着
-
全部都是救急线程(60s 后没有任务就回收)
-
救急线程可以无限创建
②队列采用了 SynchronousQueue :它没有容量,没有线程来取是放不进去的(一手交钱、一手交货)
③整个线程池表现为线程数会根据任务量不断增长,没有上限,当任务执行完毕,空闲 1分钟后释放线程。
使用场景:适合任务数比较密集,但每个任务执行时间较短的情况
③newSingleThreadExector
线程数固定为1,也就只有一个核心线程数!
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));
}
用场景:
希望多个任务排队执行。线程数固定为 1,任务数多于 1 时,会放入无界队列排队。任务执行完毕,这唯一的线程也不会被释放。
注意:
①和自己创建单线程执行任务的区别:我们自己创建一个单线程执行任务,如果任务失败而终止后是没有任何补救措施的,而这个线程池还可以再创建一个新的核心线程来继续执行任务,保证正常工作。
②newSingleThreadExecutor 和 newFixedThreadPool(1) 区别:
-
newSingleThreadExecutor() 线程个数始终为 1 ,不能修改:FinalizableDelegatedExecutorService 应用的是装饰器模式,只对外暴露了 ExecutorService 接口,因此不能调用 ThreadPoolExecutor 中特有的方法
-
newFixedThreadPool(1) 初始时为1,以后还可以修改:对外暴露的是 ThreadPoolExecutor 对象,可以强转后调用 setCorePoolSize 等方法进行修改。
4)提交任务
// 执行任务,Runnable没有返回值,也无法抛异常
void execute(Runnable command);
// 提交任务 task,用返回值 Future 获得任务执行结果,主线程可以执行 FutureTask.get()(阻塞等待)方法来等待任务执行完成;Callable有返回值,也可以抛异常!!
<T> Future<T> submit(Callable<T> task);
// 提交 tasks 中所有任务
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
// 提交 tasks 中所有任务,带超时时间
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
// 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消(找到一个最先执行的任务)
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
// 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消,带超时时间
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
submit
:
private static void method1(ExecutorService pool) throws InterruptedException, ExecutionException {
Future<String> future = pool.submit(() -> {
log.debug("running");
Thread.sleep(1000);
return "ok";
});
log.debug("{}", future.get());//主线程在这阻塞着等待,结果
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(1);
method1(pool);
}
invokeAll用法
:
private static void method2(ExecutorService pool) throws InterruptedException {
List<Future<String>> futures = pool.invokeAll(Arrays.asList(
() -> {
log.debug("begin");
Thread.sleep(1000);
return "1";
},
() -> {
log.debug("begin");
Thread.sleep(500);
return "2";
},
() -> {
log.debug("begin");
Thread.sleep(2000);
return "3";
}
));
futures.forEach( f -> {
try {
log.debug("{}", f.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
});
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(1);
method2(pool);
}
5)关闭线程池
①shutdown
特点:
调用shutdown
后:线程池状态变为 SHUTDOWN
-
不会再接受新任务,但是会把已经提交的任务执行完(包括等待队列里的)
-
这个方法也不会阻塞调用线程(比如主线程)的执行
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
// 修改线程池状态
advanceRunState(SHUTDOWN);
// 仅会打断空闲线程
interruptIdleWorkers();
onShutdown(); // 扩展点 ScheduledThreadPoolExecutor
} finally {
mainLock.unlock();
}
// 尝试终结(没有运行的线程可以立刻终结),还有运行的线程主线程也不会等,等它们自己运行完结束就好了。
tryTerminate();
}
②shutdownNow
特点:
-
线程状态变为STOP
-
不会接收新任务,而且会将队列中的任务返回
-
会用interrupt的方式中断正在执行的任务
public List<Runnable> shutdownNow() {
List<Runnable> tasks;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
// 修改线程池状态
advanceRunState(STOP);
// 打断所有线程
interruptWorkers();
// 获取队列中剩余任务
tasks = drainQueue();
} finally {
mainLock.unlock();
}
// 尝试终结,会成功
tryTerminate();
return tasks;
}