From 8df72611279dfa3486206e5d1d7e3ed6ff157a66 Mon Sep 17 00:00:00 2001 From: marr97 Date: Sat, 14 Mar 2026 13:09:34 +0300 Subject: [PATCH] queue: first version --- .../tasks/queue/BoundedBlockingQueue.java | 43 ++++++++++++++++--- 1 file changed, 36 insertions(+), 7 deletions(-) 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..ed021ad6 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,54 @@ package hse.java.lectures.lecture6.tasks.queue; +import java.util.LinkedList; +import java.util.Queue; + public class BoundedBlockingQueue { + private int capacity = 0; + private final Object monitor = new Object(); + private final Queue blockingQueue = new LinkedList<>(); public BoundedBlockingQueue(int capacity) { - + if (capacity <= 0) { + throw new IllegalArgumentException(); + } else { + this.capacity = capacity; + } } - public void put(T item) { - + public void put(T item) throws InterruptedException { + if (item == null) { + throw new NullPointerException(); + } else { + synchronized (monitor) { + while (blockingQueue.size() == capacity) { + monitor.wait(); + } + blockingQueue.add(item); + monitor.notifyAll(); + } + } } - public T take() { - return null; + public T take() throws InterruptedException { + synchronized (monitor) { + while (blockingQueue.isEmpty()) { + monitor.wait(); + } + T item = blockingQueue.remove(); + monitor.notifyAll(); + return item; + } } public int size() { - return 0; + synchronized (monitor) { + return blockingQueue.size(); + } } public int capacity() { - return 0; + return capacity; } }