加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如果有太多的数据需要处理,我如何使ThreadPoolExecutor

发布时间:2020-12-14 05:04:42 所属栏目:Java 来源:网络整理
导读:我从队列服务器获取数据,我需要处理它并发送确认.这样的东西 while (true) { queueserver.get.data ThreadPoolExecutor //send data to thread queueserver.acknowledgement 我不完全明白线程中会发生什么,但我认为这个程序获取数据,发送线程然后立即确认.所
我从队列服务器获取数据,我需要处理它并发送确认.这样的东西
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的主要缺点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读