天天看点

手写LinkedBlockingQueue

原作者:老铁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<E> {
	private NodeV1<E> head;
	private NodeV1<E> 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> e = new NodeV1<E>(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<E> h = head;
		NodeV1<E> 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<E> node = new NodeV1<E>(e);
		tail = tail.next = node;
		count++;
		empty.signalAll();
	}
}

class NodeV1<E> {
	public E data;
	public NodeV1<E> next;

	public NodeV1(E data) {
		this.data = data;
	}
}


           

继续阅读