Java實現阻塞佇列
阿新 • • 發佈:2020-11-24
public class ArrayBlockQueue { public int size; private volatile Object[] items; private volatile int pollPoint = 0; private volatile int addPoint = 0; private volatile int count = 0; private Object addLock = new Object(); private Object pollLock = new Object(); publicArrayBlockQueue(int size) { this.size = size; this.items = new Object[size]; } public void add(Object item) { synchronized (addLock) { while (count >= size) { try { addLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } items[addPoint]= items; addPoint = (addPoint + 1) % size; count++; if (count == 1) { synchronized (pollLock) { pollLock.notifyAll(); } } } } public Object poll() { synchronized (pollLock) {while (count == 0) { try { pollLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Object value = items[pollPoint]; pollPoint = (pollPoint + 1) % size; count--; if (count == (size - 1)) { synchronized (addLock) { addLock.notifyAll(); } } return value; } } }
參考連結:https://segmentfault.com/a/1190000020005820?utm_source=tag-newest