public class MyThreadPool2 {
/**
* 线程池的四种拒绝策略
*/
public static void main(String[] args) {
new MyThreadPool2().req(new MyThreadPool2().four());
}
/**
* 第一种拒绝策略:抛异常
* Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task com.dawn.one.MyThreadPool2$$Lambda$1/764977973@3feba861 rejected from java.util.concurrent.ThreadPoolExecutor@5b480cf9[Running, pool size = 5, active threads = 0, queued tasks = 0, completed tasks = 12]
* 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.dawn.one.MyThreadPool2.req(MyThreadPool2.java:36)
* at com.dawn.one.MyThreadPool2.main(MyThreadPool2.java:14)
*/
public RejectedExecutionHandler one(){
return new ThreadPoolExecutor.AbortPolicy();
}
/**
* 第二种拒绝策略:无异常,哪里来,那里去
*/
public RejectedExecutionHandler two(){
return new ThreadPoolExecutor.CallerRunsPolicy();
}
/**
* 第三种拒绝策略:无异常,优先抛弃最老的任务,并且执行当前任务
*/
public RejectedExecutionHandler three(){
return new ThreadPoolExecutor.DiscardOldestPolicy();
}
/**
* 第四种拒绝策略:无异常,直接抛弃需要等待的代码
*/
public RejectedExecutionHandler four(){
return new ThreadPoolExecutor.DiscardPolicy();
}
/**
* 业务代码
* @param handler 四种拒绝方式
*/
public void req(RejectedExecutionHandler handler){
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
2,
5,
2l,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(2),
Executors.defaultThreadFactory(),
handler
);
for (int i = 0; i < 200; i++) {
int num = i;
threadPoolExecutor.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t 顾客真正处理业务"+num);
});
}
threadPoolExecutor.shutdown();
}
}
Java 线程池中的四种拒绝策略
最新推荐文章于 2024-08-05 17:02:34 发布