线程池中的四个任务拒绝策略的区别
DiscardPolicy
public class Task implements Runnable{
private final int index;
public Task(int index){
this.index = index;
}
public void run() {
System.out.println(Thread.currentThread().getName()+" "+index);
}
}
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPool06 {
public static void main(String[] args) {
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1,1,0L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(1),
new ThreadPoolExecutor.DiscardPolicy());
try {
threadPool.execute((new Task(1)));
threadPool.execute((new Task(2)));
threadPool.execute((new Task(3)));
}catch (RejectedExecutionException e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
}
- 输出结果
CallerRunsPolicy
- 使用调用者线程直接执行被拒绝的任务
- 拒绝策略改为CallerRunsPolicy
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPool06 {
public static void main(String[] args) {
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1,1,0L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(1),
new ThreadPoolExecutor.CallerRunsPolicy());
try {
threadPool.execute((new Task(1)));
threadPool.execute((new Task(2)));
threadPool.execute((new Task(3)));
}catch (RejectedExecutionException e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
}
- 输出结果
AbortPolicy
- 默认的拒绝策略,抛出RejectedExecutionException异常
- 拒绝策略改为AbortPolicy
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPool06 {
public static void main(String[] args) {
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1,1,0L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(1),
new ThreadPoolExecutor.AbortPolicy());
try {
threadPool.execute((new Task(1)));
threadPool.execute((new Task(2)));
threadPool.execute((new Task(3)));
}catch (RejectedExecutionException e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
}
- 输出结果
DiscardOldestPolicy
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPool06 {
public static void main(String[] args) {
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1,1,0L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(2),
new ThreadPoolExecutor.DiscardOldestPolicy());
try {
threadPool.execute((new Task(1)));
threadPool.execute((new Task(2)));
threadPool.execute((new Task(3)));
threadPool.execute((new Task(4)));
}catch (RejectedExecutionException e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
}
- 输出结果
参考地址
线程池视频讲解07