作者:万承裕常明 | 来源:互联网 | 2023-10-13 12:32
原作者:老铁123
出处:https://blog.csdn.net/qewgd/article/details/88364742
本文归作者【老铁123】和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
LinkedBlockingQueue基于链表的阻塞队列,生产者消费者模型应用。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class LinkedBlockingQueueV1 {private NodeV1 head;private NodeV1 tail;private Lock lock = new ReentrantLock();private Condition full = lock.newCondition();private Condition empty = lock.newCondition();private int capacity;private int count = 0;public LinkedBlockingQueueV1() {this(Integer.MAX_VALUE);}public LinkedBlockingQueueV1(int capacity) {this.capacity = capacity;NodeV1 e = new NodeV1(null);head = tail = e;}public void put(E e) throws InterruptedException {lock.lock();try {while (count == capacity)full.await();enqueue(e);} finally {lock.unlock();}}public E take() throws InterruptedException {lock.lock();try {while (count == capacity)empty.await();return dequeue();} finally {lock.unlock();}}private E dequeue() {NodeV1 h = head;NodeV1 first = h.next;h.next = h;head = first;E data = first.data;first.data = null;count--;full.signalAll();return data;}private void enqueue(E e) {NodeV1 node = new NodeV1(e);tail = tail.next = node;count++;empty.signalAll();}
}class NodeV1 {public E data;public NodeV1 next;public NodeV1(E data) {this.data = data;}
}