package 多线程并发; import java.util.Stack; /** * Created by z84102272 on 2018/7/17. */ public class BlockQueueImpl { private final static Object pushLock = new Object(); //push的锁 private final static Object popLock = new Object(); //pop的锁 private Stack<Object> stack; //存储数据 public BlockQueueImpl(){ stack = new Stack<>(); } /** * push锁 */ private void pushLock(){ synchronized (pushLock){ try{ pushLock.wait(); }catch (Exception e){ e.printStackTrace(); } } } /** * 释放push锁 */ private void pushUnlock(){ pushLock.notify(); } private void popLock(){ try { popLock.wait(); }catch (Exception e){ e.printStackTrace(); } } private void popUnlock(){ popLock.notify(); } public synchronized void push(Object o){ int MAX_SIZE = 3; if (stack.size() >= MAX_SIZE){ pushLock(); } stack.push(o); popUnlock(); } public Object pop(){ if (stack.size()==0){ popLock(); } Object o = stack.pop(); pushUnlock(); return o; } }