MyBlockingQueue 代码
package com.kms.test; import java.util.LinkedList; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class MyBlockingQueue<E> { LinkedList<E> list; int size; // 队列大小,可指定,默认为16 ReentrantLock lock = new ReentrantLock(); // 可重入锁 Condition nonFull = lock.newCondition(); // 非满条件 Condition nonEmpty = lock.newCondition(); // 非空条件 MyBlockingQueue(){ this(16); } MyBlockingQueue(int size){ this.size = size; this.list = new LinkedList(); } public void enqueue(E e) throws InterruptedException{ lock.lock(); try{ while(list.size() == size){ System.out.println("队列已满,当前数量为: "+list.size()); nonFull.await(); } list.add(e); System.out.println("入队: "+e); nonEmpty.signal(); // 非空,唤醒在nonEmpty条件上等待的线程 }finally{ lock.unlock(); } } public E dequeue() throws InterruptedException{ lock.lock(); try{ while(list.size() == 0){ System.out.println("队列为空"); nonEmpty.await(); } E e = list.pop(); System.out.println("出队: "+e); nonFull.signal(); // 唤醒在nonFull条件上等待的线程 return e; }finally{ lock.unlock(); } } }
简单测试类
package com.kms.test; public class Test7 { static MyBlockingQueue queue = new MyBlockingQueue<Integer>(); public static void main(String[] args) { // TODO Auto-generated method stub new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub try { Thread.sleep(3000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for(int i = 0; i < 3; i++){ try { queue.dequeue(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); for(int i = 0; i < 20; i ++){ try { queue.enqueue(new Integer(i)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
运行结果