多线程(四)--wait/notify模拟queue

public class MyQueue {

	//1.需要一个承装元素的集合
	private final LinkedList<Object> list = new LinkedList<>();

	//2.需要一个计数器
	private AtomicInteger count = new AtomicInteger(0);

	//3.需要指定上限和下限
	private final int minSize = 0;
	private final int maxSize;

	//4.构造方法
	public MyQueue(int size) {
		this.maxSize = size;
	}

	//5.初始化一个对象,用于加锁
	private final Object lock = new Object();

	//put(anObject):把anObject加到BlockingQueue里,如果BlockingQueue没有空间,则调用此方法的线程阻塞,直到BlockingQueue有空间
	public void put(Object obj) {
		synchronized (lock) {
			while (count.get() == this.maxSize) {
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			//1.加入元素
			list.add(obj);
			System.out.println("新加入的元素为:" + obj);
			//2.计数器加1
			count.incrementAndGet();
			//3.通知另外一个线程(唤醒)
			lock.notify();
		}
	}

	//take:取走BlockingQueue里排在首位的对象,如果BlockingQueue为空,阻断、进入等待状态,直到BlockingQueue有新的元素加入
	public Object take() {
		Object ret = null;

		synchronized (lock) {
			while (count.get() == this.minSize) {
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			//
			ret = list.removeFirst();
			System.out.println("take的元素:" + ret);
			count.decrementAndGet();
			lock.notify();
		}

		return ret;
	}

	public int getSize() {
		return this.count.get();
	}

	public static void main(String[] args) throws InterruptedException {
		MyQueue mq = new MyQueue(5);
		mq.put("a");
		mq.put("b");
		mq.put("c");
		mq.put("d");
		mq.put("e");

		System.out.println("当前容器的长度:" + mq.getSize());

		Thread t1 = new Thread(() -> {
			mq.put("f");
			mq.put("g");
		}, "t1");

		t1.start();

		Thread.sleep(2000);

		Thread t2 = new Thread(() -> {
			Object o1 = mq.take();
			Object o2 = mq.take();
		}, "t2");
		t2.start();
	}
}

猜你喜欢

转载自blog.csdn.net/csdn_kenneth/article/details/82775291