package thread; import java.util.concurrent.*; import java.util.stream.IntStream; public class ThreadPoolExecutorDemo { public static void main(String[] args) { int corePoolSize = 10; int maxPoolSize = 10; long keepAliveTime = 1000; TimeUnit timeUnit = TimeUnit.MILLISECONDS; BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(1000); // 队列满之后,则丢弃队列中的旧任务 // RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardOldestPolicy(); // 队列满之后,则丢弃新的任务 // RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardPolicy(); // 队列满之后,会将任务分配给调用者线程。所有任务都会得到执行 // RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy(); // 队列满之后,程序进入阻塞。是ThreadPoolExecutor的默认拒绝策略 RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy(); ExecutorService es = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue, handler); IntStream.range(1, 10000).forEach(i -> es.submit(new MyTask("TaskOne_" + i))); es.shutdown(); } }
自定义拒绝策略,新建线程来处理无法加入队列的任务。是Netty使用的拒绝策略。
package thread;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
public class NewThreadRunsPolicy implements RejectedExecutionHandler {
public NewThreadRunsPolicy() {
super();
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
Thread t = new Thread(r, "Temporary task executor");
t.start();
} catch (Throwable t) {
throw new RejectedExecutionException("Failed to start a new thread", t);
}
}
}
相关资料:java线程池ThreadPoolExecutor八种拒绝策略浅析_chihujiang3132的博客-CSDN博客z