常用线程池 及其API

1.newFixedThreadPool

image1

2.newCachedThreadPool

适合任务分布密集,

但是耗时短的

image2

3.newSingleThreadExecutor

确保始终有一个线程可用,

并且有兜底策略

基于装饰者模式,通过强制类型转换只对外暴露接口,使得ThreadPoolExecutor的方法不可用

其参数不可变

image3
开启线程池提交任务 image4
1.execuate 无返回值 consumer
2.submit 有返回值

Future<T> submit(Callable<T>)

--->Callable接口有返回值重写call方法, 并且返回

  1. invokeAll 返回future集合

可以设置超时时间

<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
4.invokeAny
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
结束线程
shutdown 停止接收task, 但不停止正在运行的task
shutdownNow 停止接受task, 且会停止正在云顶的task