java.util.concurrent.RejectedExecutionException
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1768)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:767)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:658)
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
通过如下方式创建线程池:
AbstractExecutorService executor=new ThreadPoolExecutor(3,10,30L,TimeUnit.SECONDS,new SynchronousQueue(),new ExecutorThreadFactory("ThrowableThreadPoolExecutor"),new AbortPolicy());
new ExecutorThreadFactory("ThrowableThreadPoolExecutor")简单的封装了ThreadFactory
由于SynchronousQueue并不是一个真正的队列,而是一种管理直接在线程间移交信息的机制,为了把一个元素放入到SynchronousQueue中,必须有另一个线程正在等待接受移交的任务。如果没有这样一个线程,只要当前池的大小还小于最大值,ThreadPoolExcutor就会创建一个新的线程;否则根据饱和策略,任务会被拒绝。而设置的饱和策略恰恰是new AbortPolicy(),当线程池满了后,execute抛出未检查的RejectedExecutionException,线程丢失。可以通过捕获该异常做相应的补救处理。
另外的处理方式是设置线程池的队列的饱和策略,线程池创建如下:
AbstractExecutorService executor = new ThrowableThreadPoolExecutor(10,40, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue
new ExecutorThreadFactory("ThrowableThreadPoolExecutor"), new ThreadPoolExecutor.CallerRunsPolicy());
当任务向线程池请求要分配线程时,线程池处理如下:
1、如果此时线程池中的数量小于corePoolSize,即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务
2、如果此时线程池中的数量等于 corePoolSize,但是缓冲队列 workQueue未满,那么任务被放入缓冲队列