下面是建立一个线程池的基本语法,最后一个参数是线程池的拒绝策略。Jdk默认实现了4个拒绝策略。在下面四张图片中可以看到。
ThreadPoolExecutor pool = new ThreadPoolExecutor(3,
6,
3000,
TimeUnit.MILLISECONDS,
new LinkedBlockingDeque<Runnable>(),
new ThreadFactory(){
@Override
public Thread newThread(Runnable r) {
ThreadGroup group = Thread.currentThread().getThreadGroup();
Thread thread =new Thread(group, r, "Thread-"+count.getAndIncrement());
return thread;
}
},
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
throw new RuntimeException("任务被拒绝");
}
});