如果需要处理的数据太多,如何让 ThreadPoolExecutor 命令等待?
BlockingQueue
您可以使用带有限制的a 而不是开放式队列:
BlockingQueue<Date> queue = new ArrayBlockingQueue<Date>(200);
就提交给 的作业而言,您可以创建自己的ExecutorService
,而不是使用使用无界队列创建的默认ExecutorService
s :Executors
return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(200));
一旦队列填满,它将导致它拒绝任何提交的新任务。您将需要设置一个RejectedExecutionHandler
提交到队列的。就像是:
final BlockingQueue queue = new ArrayBlockingQueue<Runnable>(200);
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS, queue);
// by default (unfortunately) the ThreadPoolExecutor will throw an exception
// 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);
// check afterwards and throw if pool shutdown
if (executor.isShutdown()) {
throw new RejectedExecutionException(
"Task " + r + " rejected from " + e);
}
}
});
我认为 Java 没有ThreadPoolExecutor.CallerBlocksPolicy
.