线程池
使用线程池可以不用频繁的创建线程,而是复用已经创建的线程,这样可以降低开销、控制最大并发数
四种线程池
Executors.newSingleThreadExecutor();
只包含单线程的线程池,确保任务按顺序执行Executors.newFixedThreadPool(5);
创建一个固定大小的线程池,corePoolSize和maximumPoolSize相等,线程池中的线程不会被回收newScheduledThreadPool(int corePoolSize);
支持定时任务和周期性任务调度Executors.newCachedThreadPool();
缓存线程池(无界线程池),corePoolSize为0,maximumPoolSize为Integer.MAX_VALUE,空闲线程存活时间默认为60秒
源码
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
三个源码的均是通过ThreadPoolExecutor
创建线程池,看下ThreadPoolExecutor
源码
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;
}
线程池七大参数
由上述源码得知有7个参数
1、corePoolSize:核心线程数,线程池中始终存活的最小线程数,即使这些线程处于空闲状态,也不会被销毁
2、maximumPoolSize:最大线程数,超过此值后新的任务将触发拒绝策略
3、keepAliveTime:空闲线程存活时间,线程池中的线程数大于核心线程数后,超过此时间会回收多余的线程
4、timeUnit:时间单位
5、workQueue:工作队列,存放执行任务的队列
6、threadFactory:线程工厂,用于定制线程的创建
7、Handler:拒绝策略
四种拒绝策略
提供了四个预定义的处理程序策略:
在默认ThreadPoolExecutor.AbortPolicy ,处理程序会引发运行RejectedExecutionException后排斥反应,抛出异常。
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
try {
for (int i = 1; i <= 9; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"----ok");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
executorService.shutdown();
}
}
执行结果
pool-1-thread-2----ok
pool-1-thread-2----ok
pool-1-thread-2----ok
pool-1-thread-2----ok
pool-1-thread-1----ok
pool-1-thread-3----ok
pool-1-thread-5----ok
pool-1-thread-4----ok
java.util.concurrent.RejectedExecutionException: Task com.song.pool.Demo02$$Lambda$1/1831932724@7699a589 rejected from java.util.concurrent.ThreadPoolExecutor@58372a00[Running, pool size = 5, active threads = 4, queued tasks = 0, completed tasks = 4]
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 com.song.pool.Demo02.main(Demo02.java:23)
在ThreadPoolExecutor.CallerRunsPolicy中,调用execute本身的线程运行任务。 这提供了一个简单的反馈控制机制,将降低新任务提交的速度,哪来的回哪由调用者处理。
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy()
);
try {
for (int i = 1; i <= 9; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"----ok");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
executorService.shutdown();
}
}
执行结果
pool-1-thread-1----ok
main----ok
pool-1-thread-1----ok
pool-1-thread-5----ok
pool-1-thread-3----ok
pool-1-thread-2----ok
pool-1-thread-5----ok
pool-1-thread-1----ok
pool-1-thread-4----ok
在ThreadPoolExecutor.DiscardPolicy中 ,简单地删除无法执行的任务。
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardPolicy()
);
try {
for (int i = 1; i <= 9; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"----ok");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
executorService.shutdown();
}
}
执行结果
pool-1-thread-1----ok
pool-1-thread-4----ok
pool-1-thread-1----ok
pool-1-thread-3----ok
pool-1-thread-2----ok
pool-1-thread-1----ok
pool-1-thread-4----ok
pool-1-thread-5----ok
在ThreadPoolExecutor.DiscardOldestPolicy中 ,如果执行程序没有关闭,则工作队列头部的任务被删除,然后重试执行(可能会再次失败,导致重复)
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy()
);
try {
for (int i = 1; i <= 9; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"----ok");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
executorService.shutdown();
}
}
执行结果
pool-1-thread-1----ok
pool-1-thread-2----ok
pool-1-thread-3----ok
pool-1-thread-3----ok
pool-1-thread-4----ok
pool-1-thread-5----ok
pool-1-thread-3----ok
pool-1-thread-1----ok
pool-1-thread-4----ok