可能会帮助您的一个技巧是分配一个RejectedExecutionHandler
使用相同线程的作业,以将作业提交到阻塞队列。这将阻塞当前线程,并消除对某种循环的需要。
这是从该答案中复制的拒绝处理程序。
final BlockingQueue queue = new ArrayBlockingQueue<Runnable>(200);
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS, queue);
// by default (unfortunately) the ThreadPoolExecutor will call the rejected
// handler when you submit the 201st job, to have it block you do:
threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// this will block if the queue is full
executor.getQueue().put(r);
}
});
然后,您应该能够使用的核心/最大线程数的,只要你意识到有界阻塞队列你使用首先填满芯线上面创建的线程之前。因此,如果您有10个核心线程,并且希望第11个作业启动第11个线程,那么您将需要具有大小为0的阻塞队列(可能是aSynchronousQueue
)。我觉得这是本来不错的ExecutorService
课程的真正限制。