Skip to content

Commit

Permalink
Hero - Multithreading - Consumer Producer problem
Browse files Browse the repository at this point in the history
  • Loading branch information
kon3ktor committed Oct 23, 2024
1 parent f2e418b commit 3c3487b
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/com/hero/multithreading/producerconsumer/Message.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.hero.multithreading.producerconsumer;

public class Message {

private String message;

public Message(String message) {
this.message = message;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}
28 changes: 28 additions & 0 deletions src/com/hero/multithreading/producerconsumer/MessageConsumer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.hero.multithreading.producerconsumer;

import java.util.concurrent.BlockingQueue;

public class MessageConsumer implements Runnable {

private BlockingQueue<Message> queue;

public MessageConsumer(BlockingQueue<Message> queue) {
this.queue = queue;
}

@Override
public void run() {
try {
Message message;
while (!"exit".equals((message = queue.take()).getMessage())) {
Thread.sleep(100);
System.out.println("Message is consumed: " + message.getMessage());
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}



}
}
31 changes: 31 additions & 0 deletions src/com/hero/multithreading/producerconsumer/MessageProducer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.hero.multithreading.producerconsumer;

import java.util.concurrent.BlockingQueue;

public class MessageProducer implements Runnable {

private BlockingQueue<Message> queue;

public MessageProducer(BlockingQueue<Message> queue) {
this.queue = queue;
}

@Override
public void run() {
for (int i = 0; i < 100; i++) {
Message message = new Message("" + i);
try {
queue.put(message);
System.out.println("Message added to queue: " + message.getMessage());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
try {
queue.put(new Message("exit"));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.hero.multithreading.producerconsumer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ProducerConsumerApp {

public static void main(String[] args) {
BlockingQueue<Message> queue = new ArrayBlockingQueue<>(5);
MessageProducer producer = new MessageProducer(queue);
MessageConsumer consumer = new MessageConsumer(queue);

new Thread(producer).start();
new Thread(consumer).start();

}
}

0 comments on commit 3c3487b

Please sign in to comment.