Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions src/main/java/core/basesyntax/BlockingQueue.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,23 @@ public BlockingQueue(int capacity) {
}

public synchronized void put(T element) throws InterruptedException {
// write your code here
while (queue.size() == capacity) {
wait();
}
queue.add(element);
notifyAll();
}

public synchronized T take() throws InterruptedException {
// write your code here
return null;
while (queue.isEmpty()) {
wait();
}
T element = queue.remove();
notifyAll();
return element;
}

public synchronized boolean isEmpty() {
// write your code here
return true;
return queue.isEmpty();
}
}
17 changes: 11 additions & 6 deletions src/main/java/core/basesyntax/thread/Consumer.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,25 @@
import core.basesyntax.BlockingQueue;

public class Consumer implements Runnable {
private BlockingQueue<Integer> blockingQueue;
private final BlockingQueue<Integer> blockingQueue;

public Consumer(BlockingQueue<Integer> blockingQueue) {
this.blockingQueue = blockingQueue;
}

@Override
public void run() {
while (!blockingQueue.isEmpty()) {
try {
System.out.println("Took value " + blockingQueue.take());
} catch (InterruptedException e) {
throw new RuntimeException("Consumer was interrupted!", e);
try {
while (true) {
Integer value = blockingQueue.take();
if (value == null) {
break;
}
System.out.println("Consumed " + value);
}
System.out.println("Consumer finished.");
} catch (InterruptedException e) {
System.out.println("Consumer was interrupted!");
}
}
}
10 changes: 6 additions & 4 deletions src/main/java/core/basesyntax/thread/Producer.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ public Producer(BlockingQueue<Integer> blockingQueue) {

@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
try {
for (int i = 0; i < 50; i++) {
blockingQueue.put(i);
} catch (InterruptedException e) {
throw new RuntimeException("Producer was interrupted!", e);
System.out.println("Produced " + i);
}
blockingQueue.put(null);
} catch (InterruptedException e) {
System.out.println("Producer was interrupted!");
}
}
}
Loading