JDK提供的四种拒绝策略+一种自定义拒绝策略
1.ThreadPoolExecutor.AbortPolicy()默认拒绝策略,不执行新任务抛出异常
ThreadPoolExecutor threadPoolExecutor=
new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1),
threadFactory,new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i <3 ; i++) {
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("线程名:"+Thread.currentThread().getName());
}
});
}
2.ThreadPoolExecutor.CallerRunsPolicy()把新任务交给主线程来执行
//把当前任务交给主线程来执行
ThreadPoolExecutor threadPoolExecutor=
new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1),threadFactory,new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i <3 ; i++) {
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("线程名:"+Thread.currentThread().getName());
}
});
}
3.ThreadPoolExecutor.DiscardOldestPolicy()丢弃最老的任务
//丢弃最老的任务
ThreadPoolExecutor threadPoolExecutor=
new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(8),
threadFactory,new ThreadPoolExecutor.DiscardOldestPolicy());
for (int i = 0; i <10 ; i++) {
final int fianlI=i;
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println(fianlI+"线程名:"+Thread.currentThread().getName());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
4.ThreadPoolExecutor.DiscardPolicy()丢弃(当前任务)最新的任务
//丢弃最新的任务
ThreadPoolExecutor threadPoolExecutor=
new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(8),
threadFactory,new ThreadPoolExecutor.DiscardPolicy());
for (int i = 0; i <10 ; i++) {
final int fianlI=i;
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println(fianlI+"线程名:"+Thread.currentThread().getName());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
5.new RejectedExecutionHandler() {}自定义拒绝策略
ThreadPoolExecutor threadPoolExecutor=
new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(8),
threadFactory, new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
//自定义拒绝策略,可以写到日志里面,也可以存储到数据库 ,也可以啥也不做
System.out.println("执行了拒绝策略");
}
});
for (int i = 0; i <10 ; i++) {
final int fianlI=i;
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println(fianlI+"线程名:"+Thread.currentThread().getName());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}