From f092711695d4c7dda90c3efba49c30e9e0dbee5c Mon Sep 17 00:00:00 2001 From: Dasha Date: Sat, 21 Mar 2026 14:05:26 +0300 Subject: [PATCH] queue: v1 --- .../tasks/queue/BoundedBlockingQueue.java | 33 ++++++++++++++----- 1 file changed, 25 insertions(+), 8 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 816f3ee..63dd0b8 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 @@ -2,24 +2,41 @@ public class BoundedBlockingQueue { + private final Object[] buffer; + private final int capacity; + private int head, tail, size; public BoundedBlockingQueue(int capacity) { - + if (capacity <= 0) throw new IllegalArgumentException("capacity must be > 0"); + this.capacity = capacity; + this.buffer = new Object[capacity]; } - public void put(T item) throws InterruptedException { - + public synchronized void put(T item) throws InterruptedException { + if (item == null) throw new NullPointerException("null items are not allowed"); + while (size == capacity) wait(); + buffer[tail] = item; + tail = (tail + 1) % capacity; + size++; + notifyAll(); } - public T take() throws InterruptedException { - return null; + @SuppressWarnings("unchecked") + public synchronized T take() throws InterruptedException { + while (size == 0) wait(); + T item = (T) buffer[head]; + buffer[head] = null; + head = (head + 1) % capacity; + size--; + notifyAll(); + return item; } - public int size() { - return 0; + public synchronized int size() { + return size; } public int capacity() { - return 0; + return capacity; } }