java – 如果有太多的数据需要处理,我如何使ThreadPoolExecutor命令等待?

我从队列服务器获取数据,我需要处理它并发送确认.这样的东西
while (true) {
    queueserver.get.data
    ThreadPoolExecutor //send data to thread
    queueserver.ackNowledgement

我不完全明白线程中会发生什么,但我认为这个程序获取数据,发送线程然后立即确认.所以即使我有一个限制,每个队列只能有200个未确认的项目,它只会拉得很快,它可以接收它.当我在单个服务器上编写程序时,这是很好的,但如果我使用多个工作人员,那么这成为一个问题,因为线程队列中的项目数量并不反映其完成的工作,而是它的速度可以从队列服务器获取项目.

有什么我可以做的,以某种方式使程序等待,如果线程队列充满了工作?

解决方法

我不是100%肯定我在这里了解你的问题.当然,而不是一个开放式的队列,你可以使用一个具有限制的BlockingQueue:
BlockingQueue<Date> queue = new ArrayBlockingQueue<Date>(200);

在提交给ExecutorService的作业方面,而不是使用使用无界队列的Executors创建的认ExecutorServices,您可以创建自己的:

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,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的主要缺点.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...