Created
February 25, 2017 11:04
-
-
Save ivanursul/7a7c1c0b329b70bf61719a6213f7fa37 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class QueueModel { | |
public static void main(String[] args) { | |
Queue<String> queue = new LinkedList<>(); | |
QueueMessageProducer producer = new QueueMessageProducer(queue); | |
List<QueueConsumer> consumers = new ArrayList<>(); | |
for (int i = 0; i < 3; i++ ) { | |
QueueConsumer consumer = new QueueConsumer( | |
"Consumer" + i, | |
queue | |
); | |
consumer.start(); | |
consumers.add(consumer); | |
} | |
Scanner scanner = new Scanner(System.in); | |
while(true) { | |
String message = scanner.nextLine(); | |
producer.notify(message); | |
} | |
} | |
static class QueueMessageProducer { | |
private Queue<String> queue; | |
public QueueMessageProducer(Queue<String> queue) { | |
this.queue = queue; | |
} | |
public void notify(String message) { | |
synchronized (queue) { | |
queue.add(message); | |
queue.notify(); | |
} | |
} | |
} | |
static class QueueConsumer extends Thread { | |
private Queue<String> queue; | |
public QueueConsumer(String name, Queue<String> queue) { | |
super(name); | |
this.queue = queue; | |
} | |
@Override | |
public void run() { | |
try { | |
while (true) { | |
synchronized (queue) { | |
queue.wait(); | |
} | |
synchronized (queue) { | |
if (!queue.isEmpty()) { | |
String message = queue.poll(); | |
System.out.printf( | |
"%s: Consuming message: %s%n", getName(), message | |
); | |
} | |
} | |
} | |
} catch (Exception e) { | |
System.out.printf( | |
"Exception occured: %s%n", e.toString() | |
); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment