微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐