diff --git a/src/main/java/core/basesyntax/BlockingQueue.java b/src/main/java/core/basesyntax/BlockingQueue.java index 77a20440..bd5b6b18 100644 --- a/src/main/java/core/basesyntax/BlockingQueue.java +++ b/src/main/java/core/basesyntax/BlockingQueue.java @@ -4,24 +4,33 @@ import java.util.Queue; public class BlockingQueue { - private Queue queue = new LinkedList<>(); - private int capacity; + private final Queue queue = new LinkedList<>(); + private final int capacity; public BlockingQueue(int capacity) { this.capacity = capacity; } - public synchronized void put(T element) throws InterruptedException { - // write your code here + public synchronized void put(T value) throws InterruptedException { + while (queue.size() == capacity) { + wait(); + } + + queue.offer(value); + notifyAll(); } public synchronized T take() throws InterruptedException { - // write your code here - return null; + while (queue.isEmpty()) { + wait(); + } + + T value = queue.poll(); + notifyAll(); + return value; } public synchronized boolean isEmpty() { - // write your code here - return true; + return queue.isEmpty(); } } diff --git a/src/main/java/core/basesyntax/thread/Consumer.java b/src/main/java/core/basesyntax/thread/Consumer.java index a28994fa..87682c28 100644 --- a/src/main/java/core/basesyntax/thread/Consumer.java +++ b/src/main/java/core/basesyntax/thread/Consumer.java @@ -3,7 +3,7 @@ import core.basesyntax.BlockingQueue; public class Consumer implements Runnable { - private BlockingQueue blockingQueue; + private final BlockingQueue blockingQueue; public Consumer(BlockingQueue blockingQueue) { this.blockingQueue = blockingQueue; @@ -11,7 +11,7 @@ public Consumer(BlockingQueue blockingQueue) { @Override public void run() { - while (!blockingQueue.isEmpty()) { + while (true) { try { System.out.println("Took value " + blockingQueue.take()); } catch (InterruptedException e) {