手写阻塞队列(java)

手动实现一个阻塞队列

public class blockQueue {
	 private List<Integer> container = new ArrayList<>();
	 private volatile int size;
	 private volatile int capacity;
	 private Lock lock = new ReentrantLock();
	 private final Condition isNull = lock.newCondition();
	 private final Condition isFull = lock.newCondition();
	 blockQueue(int capacity) {
	 	this.capacity = capacity;
	 }
	 public void add(int data) {
		 try {
		 	lock.lock();
			 try {
			 	while (size >= capacity) {
			 		System.out.println("阻塞队列满了");
			 		isFull.await();
			 	}
			 } catch (Exception e) {
			 	isFull.signal();
			 	e.printStackTrace();
			 }
			 ++size;
			 container.add(data);
			 isNull.signal();
		 } finally {
		 	lock.unlock();
		 }
	 }
	 public int take() {
		 try {
		 	lock.lock();
			 try {
			 	while (size == 0) {
			 		System.out.println("阻塞队列空了");
			 		isNull.await();
			 	}
			 } catch (Exception e) {
			 	isNull.signal();
			 	e.printStackTrace();
			 }
			 --size;
			 int res = container.get(0);
			 container.remove(0);
			 isFull.signal();
			 return res;
		 } finally {
		 	lock.unlock();
		 }
	 }
}
public static void main(String[] args) {
	 AxinBlockQueue queue = new AxinBlockQueue(5);
	 Thread t1 = new Thread(() -> {
	 	for (int i = 0; i < 100; i++) {
	 	queue.add(i);
	 	System.out.println("塞入" + i);
	 	try {
	 		Thread.sleep(500);
	 	} catch (InterruptedException e) {
	 		e.printStackTrace();
	 	}
	 }
	 });
	 Thread t2 = new Thread(() -> {
	 	for (; ; ) {
		 	System.out.println("消费"+queue.take());
			 try {
			 	Thread.sleep(800);
			 } catch (InterruptedException e) {
			 	e.printStackTrace();
			 }
	 	}
	 });
	 t1.start();
	 t2.start();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值