JAVA實現阻塞隊列
阿新 • • 發佈:2018-07-17
popu reat max lock pub ace static ati brush
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; } }
JAVA實現阻塞隊列