From 49bcf8c967d9b9e6217bca3c37e4edc131353ce5 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Thu, 19 Jan 2017 21:35:23 +0100 Subject: [PATCH] BAEL-382 BlocknigQueue producer consumer program --- .../concurrency/BlockingQueueUsage.java | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/concurrency/BlockingQueueUsage.java diff --git a/core-java/src/main/java/com/baeldung/concurrency/BlockingQueueUsage.java b/core-java/src/main/java/com/baeldung/concurrency/BlockingQueueUsage.java new file mode 100644 index 0000000000..e5637a724b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrency/BlockingQueueUsage.java @@ -0,0 +1,81 @@ +package com.baeldung.concurrency; + + +import java.util.Random; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +public class BlockingQueueUsage { + public static void main(String[] args) { + int BOUND = 10; + int N_PRODUCERS = 4; + int N_CONSUMERS = Runtime.getRuntime().availableProcessors(); + + + BlockingQueue queue = new LinkedBlockingQueue<>(BOUND); + + for (int i = 0; i < N_PRODUCERS; i++) { + System.out.println("new Producer"); + new Thread(new NumbersProducer(queue)).start(); + } + + for (int j = 0; j < N_CONSUMERS; j++) { + System.out.println("new Consumer"); + new Thread(new NumbersConsumer(queue)).start(); + } + } + + + //producer + static class NumbersProducer implements Runnable { + private final Random random = new Random(); + private final BlockingQueue numbersQueue; + + + public NumbersProducer(BlockingQueue numbersQueue) { + this.numbersQueue = numbersQueue; + } + + + public void run() { + try { + generateNumbers(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private void generateNumbers() throws InterruptedException { + for (int i = 0; i < 100; i++) { + numbersQueue.put(random.nextInt(100)); + } + } + } + + //consumer + static class NumbersConsumer implements Runnable { + private final BlockingQueue queue; + + public NumbersConsumer(BlockingQueue queue) { + this.queue = queue; + } + + public void run() { + try { + while (true) { + Integer number = queue.take(); + int result = fibonacci(number); + System.out.println("fibonacci result: " + result); + + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + public int fibonacci(Integer number) { + if (number <= 1) return number; + else return fibonacci(number - 1) + fibonacci(number - 2); + } + } +} \ No newline at end of file