如何让ThreadPoolExecutor命令等待数据是否需要处理太多?
我不是100%确定我在这里理解你的问题。当然,不是一个开放式的队列,你可以用它限制使用BlockingQueue
:
BlockingQueue<Date> queue = new ArrayBlockingQueue<Date>(200);
在提交给ExecutorService
就业方面,而不是使用默认的ExecutorService
小号创建使用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);
}
});
我认为这是一个重大的遗漏,Java没有ThreadPoolExecutor.CallerBlocksPolicy
。
谢谢格雷。为了澄清这一点,如果我将200个物品放入队列中,它将不会再允许,直到队列中的工作关闭为止。如果是这种情况,它只是等待我用来提交给线程的命令,直到有空间发送到阻塞队列为止? – 2012-04-27 15:32:43
如果在'BlockingQueue' @learningJava上使用'put()',那么是的,它会阻塞队列是否已满,然后在队列大小减少时继续。 – Gray 2012-04-27 15:50:17
+1:另一种选择是让RejectedExecutionHandler运行该任务。即'r.run();' – 2012-04-27 16:37:09