Java线程池的四种策略
⽂章⽬录
1.AbortPolicy
默认策略,直接跑出异常阻⽌系统正常运⾏
⽰例代码:
ExecutorService threadPool =new ThreadPoolExecutor(2,5,1,
TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>(3),
Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
for(int i =0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"\t办理业务");
});
}
这⾥循环8次以下是没问题的,已到10次,就报错了
pool-1-thread-3办理业务
pool-1-thread-3办理业务
pool-1-thread-3办理业务
pool-1-thread-3办理业务
pool-1-thread-5办理业务
pool-1-thread-4办理业务
pool-1-thread-1办理业务
pool-1-thread-2办理业务
Exception in thread "main" urrent.RejectedExecutionException: Task mst.VolatileDemo$$Lambda$1/142257191@7229724f rejected from jav urrent.ThreadPoolExecutor@4c873330[Running, pool size =5, active threads =4, queued tasks =0, completed tasks =4]
at urrent.jectedExecution(ThreadPoolExecutor.java:2063)
at ject(ThreadPoolExecutor.java:830)
at ute(ThreadPoolExecutor.java:1379)
at mst.VolatileDemo.main(VolatileDemo.java:18)
2.CallerRunsPolicy
“调⽤者运⾏”⼀种调节机制,该策略既不会抛弃任务,也不会抛出异常,⽽是将任务回馈⾄发起⽅⽐如main线程
⽰例代码:
ExecutorService threadPool =new ThreadPoolExecutor(2,5,1,    TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
for(int i =0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"\t办理业务");
});
}
结果:
main 办理业务
main 办理业务
main 办理业务
main 办理业务
main 办理业务
main 办理业务
main 办理业务
main 办理业务
pool-1-thread-5办理业务
pool-1-thread-2办理业务
pool-1-thread-1办理业务
main 办理业务
java线程池创建的四种
pool-1-thread-5办理业务
pool-1-thread-3办理业务
pool-1-thread-4办理业务
3.DiscardOldestPolicy
抛弃队列中等待最久的任务,然后把当前任务加⼊队列中尝试再次提交当前任务
4.DiscardPolicy
直接丢弃任务,不给予任何处理也不跑出异常,如果允许任务丢失,这是最好的⼀种⽅案

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。