手写ArrayBlockingQueue

个人分类: 算法
编辑
原作者:老铁123   
出处:https://blog.csdn.net/qewgd/article/details/88363745 
本文归作者【老铁123】和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

ArrayBlockingQueue基于数组的阻塞队列,生产者消费者模型应用。

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ArrayBlockingQueue<E> {
	private Object[] table;
	private int capacity;
	private int count = 0;
	private int putIndex = 0;
	private int takeIndex = 0;

	private Lock lock;
	private Condition full;
	private Condition empty;

	public ArrayBlockingQueue(int capacity) {
		this.capacity = capacity;
		this.table = new Object[capacity];
		this.lock = new ReentrantLock();
		this.full = lock.newCondition();
		this.empty = lock.newCondition();
	}

	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 == 0)
				empty.await();
			return dequeue();
		} finally {
			lock.unlock();
		}
	}

	private E dequeue() {
		@SuppressWarnings("unchecked")
		E e = (E) table[takeIndex];
		table[takeIndex] = null;
		if (++takeIndex == capacity)
			takeIndex = 0;
		count--;
		full.signalAll();
		return e;
	}

	private void enqueue(E e) {
		table[putIndex] = e;
		if (++putIndex == capacity)
			putIndex = 0;
		count++;
		empty.signalAll();
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值