线程池四种拒绝策略
- AbortPolicy 直接抛异常
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
- DiscardPolicy 丢弃不处理
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
- DiscardOldestPolicy 放弃最老的任务,加入当前任务
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
- CallerRunsPolicy 执行当前任务
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
线程池实例
package xiezhewan;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by yuxi on 2018/1/24.
*/
public class ThreadPoolDemo {
public static void main(String[] args) {
// 线程池核心线程数为1 延时为0 队列为有界队列长度为1, 拒绝策略为直接抛异常
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
0, TimeUnit.MICROSECONDS,
new ArrayBlockingQueue(1), new ThreadPoolExecutor.AbortPolicy());
try {
for (int i = 0; i < 10; i++) {
threadPoolExecutor.submit(() -> {
try {
System.out.println("hello");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
} catch (Exception e) {
e.printStackTrace();
threadPoolExecutor.shutdown();
}
}
}
可以看到结果为:
hello
java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@31221be2 rejected from java.util.concurrent.ThreadPoolExecutor@377dca04[Running, pool size = 1, active threads = 1, queued tasks = 1, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at xiezhewan.ThreadPoolDemo.main(ThreadPoolDemo.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
hello