Java Blocking Queue 源码实现 - 线程安全数据结构
以下是Java中阻塞队列的源码实现:
import java.util.LinkedList;
import java.util.Queue;
public class BlockingQueue<T> {
private Queue<T> queue = new LinkedList<>();
private int capacity;
public BlockingQueue(int capacity) {
this.capacity = capacity;
}
public synchronized void enqueue(T item) throws InterruptedException {
while (queue.size() == capacity) {
wait();
}
if (queue.size() == 0) {
notifyAll();
}
queue.offer(item);
}
public synchronized T dequeue() throws InterruptedException {
while (queue.size() == 0) {
wait();
}
if (queue.size() == capacity) {
notifyAll();
}
return queue.poll();
}
}
上述代码中,我们使用一个LinkedList作为底层数据结构来实现队列。enqueue方法用于将元素添加到队列中,如果队列已满,则会等待直到队列有空闲空间。dequeue方法用于从队列中取出元素,如果队列为空,则会等待直到队列有元素可取。
在实现过程中,我们使用synchronized关键字来保证线程安全,并使用wait()和notifyAll()方法来实现线程的等待和唤醒。
这是一个简单的阻塞队列的实现,你可以根据自己的需求进行扩展和优化。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pMhc 著作权归作者所有。请勿转载和采集!