程序代码如下:
public class MyQueue{ //1. 提供集合容器 private List list = new ArrayList (); //2. 提供计数器 private AtomicInteger counter = new AtomicInteger(); //3. 提供 上限 下限 private int MAX; private int MIN = 0; //4. 提供锁对象 private Object lock = new Object(); public MyQueue(int max){ this.MAX = max; } //5. put public void put(E e){ synchronized (lock){ while (counter.get() == MAX){ try { lock.wait(); } catch (InterruptedException e1) { e1.printStackTrace(); } } list.add(e); System.out.println("put " + e); counter.incrementAndGet(); lock.notify(); } } //6. take public E take(){ E e = null; synchronized (lock){ while (counter.get() == MIN){ try { lock.wait(); } catch (InterruptedException e1) { e1.printStackTrace(); } } e = list.remove(0); System.out.println("take " + e); counter.decrementAndGet(); lock.notify(); } return e; } public static void main(String[] args) { final MyQueue queue = new MyQueue (5); Thread t1 = new Thread(new Runnable() { @Override public void run() { queue.put("a"); queue.put("b"); queue.put("c"); queue.put("d"); queue.put("e"); queue.put("f"); queue.put("g"); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { queue.take(); queue.take(); } }); t1.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } t2.start(); }}
思路分析:
队列中的元素需要储存,可以简单考虑为List集合储存
既然是模拟实现阻塞队列,那么队列应该有容量限制,上限和下限
应该提供一个计数器的功能,告知什么时候队列可以写入,什么时候必须等待,最好的选择当然是Atomic类
wait/notify依赖于锁,所以提供锁对象