From 93b9a5cb37b6f74e7da67db4e984737556cd5626 Mon Sep 17 00:00:00 2001 From: maxima Date: Mon, 4 May 2026 22:48:39 +0300 Subject: [PATCH] Implement BlockingQueue via notify() and wait() synchronization methods. --- .../java/core/basesyntax/BlockingQueue.java | 39 ++++++++++++++----- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/src/main/java/core/basesyntax/BlockingQueue.java b/src/main/java/core/basesyntax/BlockingQueue.java index 77a20440..4046f7c2 100644 --- a/src/main/java/core/basesyntax/BlockingQueue.java +++ b/src/main/java/core/basesyntax/BlockingQueue.java @@ -4,24 +4,43 @@ import java.util.Queue; public class BlockingQueue { - private Queue queue = new LinkedList<>(); - private int capacity; + private final Queue queue = new LinkedList<>(); + private final Object lock = new Object(); + private final int capacity; public BlockingQueue(int capacity) { this.capacity = capacity; } - public synchronized void put(T element) throws InterruptedException { - // write your code here + public void put(T element) throws InterruptedException { + synchronized (lock) { + while (isFull()) { + lock.wait(); + } + queue.add(element); + lock.notify(); + } } - public synchronized T take() throws InterruptedException { - // write your code here - return null; + public T take() throws InterruptedException { + synchronized (lock) { + while (isEmpty()) { + lock.wait(); + } + lock.notify(); + return queue.poll(); + } } - public synchronized boolean isEmpty() { - // write your code here - return true; + public boolean isEmpty() { + synchronized (lock) { + return queue.isEmpty(); + } + } + + public boolean isFull() { + synchronized (lock) { + return queue.size() == capacity; + } } }