Created
March 24, 2020 15:10
-
-
Save njofce/a1c20fd1d83cd3f60b2bb2d82d3a4c06 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Buffer<T> { | |
| List<T> items; | |
| private int capacity; | |
| private Lock canProduce = new ReentrantLock(); | |
| private Lock canConsume= new ReentrantLock(); | |
| public Buffer(int capacity){ | |
| this.items = new ArrayList<>(capacity); | |
| this.capacity = capacity; | |
| } | |
| public synchronized T getItem() throws InterruptedException { | |
| T item = null; | |
| while(items.size() == 0) | |
| wait(); | |
| item = items.remove(items.size() - 1); | |
| notifyAll(); | |
| return item; | |
| } | |
| public synchronized void addItem(T item) throws InterruptedException { | |
| while (items.size() == capacity) | |
| wait(); | |
| items.add(item); | |
| notifyAll(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment