自己动手实现阻塞队列(基于Condition)

阻塞队列的实现其实就是基于等待通知机制,下面我们进行实现:

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

//我们自己来实现个阻塞队列,主要实现方法是size(),take(),put()即可
public class MyBlockedQueue<E> {
	private ReentrantLock lock = new ReentrantLock();
	private Condition notEmpty = lock.newCondition();
	private Condition notFull = lock.newCondition();
	
	//下面是队列的属性
	private Object[] items;
	public volatile int count =0;
	MyBlockedQueue(int size){
		items = new Object[size];
	}
	
	public void put(Object obj) throws InterruptedException{
		lock.lock();
		try{
			while(count == items.length){
				System.out.println("队列已满,无法继续放入元素");
				notFull.await();
			}
			items[count++] = obj;
			System.out.println("放入元素");
			System.out.println("此时队列的元素个数为"+size());
			notEmpty.signal();
			
		}finally {
			lock.unlock(); 
		}
	}
	
	public Object take() throws InterruptedException{
		Object obj ;
		lock.lock();
		try{
			if(count == 0){
				System.out.println("队列为空,无元素可取");
				notEmpty.await();
			}
			
			obj = items[--count];
			System.out.println("取出元素");
			System.out.println("此时队列的元素个数为"+size());
			notFull.signal();
		
			return obj;
		
		}finally {
			lock.unlock();
		}
		
	}
	
	public int size(){
		return this.count;
	}
	
	public static void main(String[] args) throws InterruptedException {
		MyBlockedQueue queue = new MyBlockedQueue<>(10);
		Random r = new Random();
		Thread t1 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					while(true){
						queue.take();
						Thread.sleep(r.nextInt(900));

					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		
		Thread t2 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					while(true){
						queue.put(1);
						Thread.sleep(r.nextInt(1000));
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		t1.start();
		t2.start();
	}
	
	
	
}

 

测试结果如下:

队列为空,无元素可取
放入元素
此时队列的元素个数为1
取出元素
此时队列的元素个数为0
队列为空,无元素可取
放入元素
此时队列的元素个数为1
取出元素
此时队列的元素个数为0
队列为空,无元素可取
放入元素
此时队列的元素个数为1
取出元素
此时队列的元素个数为0
队列为空,无元素可取
放入元素
此时队列的元素个数为1
取出元素
此时队列的元素个数为0
队列为空,无元素可取
放入元素
此时队列的元素个数为1
取出元素
此时队列的元素个数为0
队列为空,无元素可取
放入元素
此时队列的元素个数为1
取出元素
此时队列的元素个数为0
放入元素
此时队列的元素个数为1
放入元素
此时队列的元素个数为2
取出元素
此时队列的元素个数为1
放入元素
此时队列的元素个数为2
取出元素
此时队列的元素个数为1
放入元素
此时队列的元素个数为2
放入元素
此时队列的元素个数为3
放入元素
此时队列的元素个数为4

 

以上为部分结果,我们解决了数组越界异常 ,实现了基础功能,put() take() 还有size(),OK!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值