基于信号量的有界缓存

匿名 (未验证) 提交于 2019-12-03 00:28:02

1、使用信号量Semaphore来实现有界缓存

2、代码如下:

/**  * BoundedBuffer  * <p/>  * Bounded buffer using \Semaphore  *  * @author Brian Goetz and Tim Peierls  */ @ThreadSafe public class SemaphoreBoundedBuffer <E> {     private final Semaphore availableItems, availableSpaces;     @GuardedBy("this") private final E[] items;     @GuardedBy("this") private int putPosition = 0, takePosition = 0;      public SemaphoreBoundedBuffer(int capacity) {         if (capacity <= 0)             throw new IllegalArgumentException();         availableItems = new Semaphore(0);         availableSpaces = new Semaphore(capacity);         items = (E[]) new Object[capacity];     }      public boolean isEmpty() {         return availableItems.availablePermits() == 0;     }      public boolean isFull() {         return availableSpaces.availablePermits() == 0;     }      public void put(E x) throws InterruptedException {         availableSpaces.acquire();         doInsert(x);         availableItems.release();     }      public E take() throws InterruptedException {         availableItems.acquire();         E item = doExtract();         availableSpaces.release();         return item;     }      private synchronized void doInsert(E x) {         int i = putPosition;         items[i] = x;         putPosition = (++i == items.length) ? 0 : i;     }      private synchronized E doExtract() {         int i = takePosition;         E x = items[i];         items[i] = null;         takePosition = (++i == items.length) ? 0 : i;         return x;     } }

转载请标明出处:基于信号量的有界缓存
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!