我们可以使用blockingqueue来实现循环缓冲区

需要循环FIFO缓冲区(如果队列已满,请始终删除最早的项目),我们可以使用blockingqueue实现它吗?

是。 请参见ArrayBlockingQueue :

 public class ArrayBlockingQueue extends AbstractQueue implements BlockingQueue, Serializable 

由数组支持的有界阻塞队列。 此队列命令元素FIFO(先进先出)。 队列的头部是队列中最长时间的元素。 队列的尾部是队列中最短时间的元素。 在队列的尾部插入新元素,队列检索操作获取队列头部的元素。

这是一个经典的“有界缓冲区”,其中固定大小的数组包含由生产者插入并由消费者提取的元素。 一旦创建,容量就无法增加。 尝试将元素放入完整队列将导致put操作阻塞; 尝试从空队列中检索元素同样会阻止。

这可能有所帮助:它是一个THREAD SAFE解决方案,其中ArrayBlockingQueue用作具有这些约束的循环环形缓冲区:

  1. 生产者:应该始终能够将数据放入缓冲区而不会被阻塞,即使缓冲区已满(即填充时从头部移除!)。 虽然如果我们希望生产者也被阻止,那么它的直截了当!

  2. 消费者:应该能够从输入中获取缓冲区,并且如果它是空的则应该被阻塞(如果你也希望这是非阻塞的话,可以使用poll())。

    //模拟环形缓冲区

     BlockingQueue bufferQueue = new ArrayBlockingQueue(MAX_SIZE); Producer Code: ... //not using put() directly as it can block this thread forever if(!bufferQueue.offer(buffer)){ //retrieve and remove the head of the queue to make space for this buffer //don't use take() as it can block this thread again if consumer took all //the data before call to take()! bufferQueue.poll(); //now put can be used safely, remember there is only one producer! bufferQueue.put(buffer); } ... Consumer Code: .. //this will block till buffer is empty //can use .poll() if don't want blocking call bufferQueue.take() ..