Created
February 25, 2017 11:02
-
-
Save ivanursul/2f64c8d3b81eeff348dbdd85c9823027 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.*; | |
import java.util.Queue; | |
public class PubSubModel { | |
public static void main(String[] args) { | |
List<Consumer> consumers = new ArrayList<>(); | |
for (int i = 0; i < 3; i++ ) { | |
Consumer consumer = new Consumer( | |
"Consumer" + i | |
); | |
consumer.start(); | |
consumers.add(consumer); | |
} | |
Scanner scanner = new Scanner(System.in); | |
while(true) { | |
String message = scanner.nextLine(); | |
for (Consumer consumer: consumers) { | |
consumer.notify(message); | |
} | |
} | |
} | |
static class Consumer extends Thread { | |
private Queue<String> queue; | |
public Consumer(String name) { | |
super(name); | |
this.queue = new LinkedList<>(); | |
} | |
@Override | |
public void run() { | |
try { | |
while (true) { | |
synchronized (queue) { | |
queue.wait(); | |
} | |
synchronized (queue) { | |
String message = queue.poll(); | |
System.out.println( | |
getName() + ": Consuming message: " + message | |
); | |
} | |
} | |
} catch (Exception e) { | |
System.out.printf( | |
"Exception occured: %s%n", e.toString() | |
); | |
} | |
} | |
public void notify(String message) { | |
synchronized (queue) { | |
queue.add(message); | |
queue.notify(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment