如何自定义BlockingQueue的阻塞行为 [英] How to customize blocking behavior of BlockingQueue
问题描述
我想创建一个阻塞队列,它根据自定义规则而不是队列中的项目数来阻止生产者。
I want to create a blocking queue which blocks producer on the basis of customized rules instead of number of items in the queue.
例如:
生产者生成一些文件并放入队列。消费者在进行一些分析后将它们转移到特定位置。
Producer produces some files and puts into a queue. Consumer transfers them to a specific location after some analysis.
对于上述情况,如果队列中的总文件大小达到某个阈值,我希望生产者等待生成新文件值。如果总大小不超过阈值,队列可以接受任意数量的文件。
For above scenario, I want producer waiting to produce new files if the size of total files in the queue reaches some threshold value. Queue can accept any number of files if the total size don't cross threshold value.
推荐答案
我可能会继承<$ div c $ c> BlockingQueue ,例如 ArrayBlockingQueue
并添加一个简单的 CountDownLatch
,将其初始化为阈值并启用各种在达到0时取
/ 删除
方法。
I would probably subclass a BlockingQueue
such as the ArrayBlockingQueue
and add a simple CountDownLatch
which is initialized to the threshold value and enables the various take
/remove
methods when reaching 0.
这篇关于如何自定义BlockingQueue的阻塞行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!