当ThreadPoolExecutor 的任务阻塞队列满了,该怎么保证任务不丢失呢?
1.修改线程池的拒绝策略为ThreadPoolExecutor.CallerRunsPolicy 采用主线程来执行任务
ExecutorService executorService = new ThreadPoolExecutor(3, 3, 6, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), new ThreadPoolExecutor.DiscardPolicy());
2.自定义拒绝策略,记录因队列满的请求参数,存储记录,可后续处理
ExecutorService executorService = new ThreadPoolExecutor(3, 3, 6, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), new MyRejectExecutionHander());
for (int i = 0; i < 100; i++) {
MyRunnable myRunnable = new MyRunnable();
myRunnable.setName(i + "");
executorService.execute(myRunnable);
}
MyRejectExecutionHander
public class MyRejectExecutionHander implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
MyRunnable myRunnable= (MyRunnable) r;
// myRunnable.
String name = myRunnable.getName();
System.out.println("拒绝了一条数据"+name);
}
}
MyRunnable name 作为参数传递
public class MyRunnable implements Runnable {
private String name;
public void setName(String name)
{
this.name = name;
}
public String getName() {
return name;
}
public void run()
{
System.out.println("hello " + name);
}
}