diff --git a/src/main/java/hse/java/lectures/lecture6/tasks/queue/BoundedBlockingQueue.java b/src/main/java/hse/java/lectures/lecture6/tasks/queue/BoundedBlockingQueue.java index 5c686cff..053e5f02 100644 --- a/src/main/java/hse/java/lectures/lecture6/tasks/queue/BoundedBlockingQueue.java +++ b/src/main/java/hse/java/lectures/lecture6/tasks/queue/BoundedBlockingQueue.java @@ -1,25 +1,53 @@ package hse.java.lectures.lecture6.tasks.queue; -public class BoundedBlockingQueue { +import java.util.ArrayDeque; +import java.util.Queue; +public class BoundedBlockingQueue { - public BoundedBlockingQueue(int capacity) { + ArrayDeque queue = new ArrayDeque<>(); + private int capacity; + private int size = 0; + Object monitor = new Object(); + public BoundedBlockingQueue(int capacity) throws IllegalArgumentException { + if (capacity <= 0) throw new IllegalArgumentException(); + this.capacity = capacity; } - public void put(T item) { + public void put(T item) throws InterruptedException, IllegalArgumentException { + if (item == null) throw new IllegalArgumentException(); + synchronized (monitor) { + if (size == capacity) { + + monitor.wait(); + } + + queue.add(item); + size++; + monitor.notifyAll(); + } } - public T take() { - return null; + public T take() throws InterruptedException { + synchronized (monitor) { + while (size == 0) { + + monitor.wait(); + + } + size--; + monitor.notifyAll(); + return queue.poll(); + } } public int size() { - return 0; + return this.size; } public int capacity() { - return 0; + return this.capacity; } }