Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.concurrent.*;
- class LanesAndBoxesAnswer {
- public static void main(String[] args) {
- BlockingQueue<Box> lane1 = new LinkedBlockingQueue<Box>();
- BlockingQueue<Box> lane2 = new LinkedBlockingQueue<Box>();
- BlockingQueue<Box> lane3 = new LinkedBlockingQueue<Box>();
- Map<Integer, BlockingQueue<Box>> lanes = new ConcurrentHashMap<Integer, BlockingQueue<Box>>();
- lanes.put(1, lane1);
- lanes.put(2, lane2);
- lanes.put(3, lane3);
- Producer p = new Producer(lanes);
- Consumer c1 = new Consumer(1, lane1);
- Consumer c2 = new Consumer(2, lane2);
- Consumer c3 = new Consumer(3, lane3);
- new Thread(p).start();
- new Thread(c1).start();
- new Thread(c2).start();
- new Thread(c3).start();
- }
- }
- class Box {
- private final int groupId;
- public Box(int groupId) {
- this.groupId = groupId;
- }
- @Override
- public String toString() {
- return "<Box " + groupId + ">";
- }
- }
- class Producer implements Runnable {
- private final Map<Integer, BlockingQueue<Box>> lanes;
- Producer(Map<Integer, BlockingQueue<Box>> lanes) {
- this.lanes = lanes;
- }
- public void run() {
- try {
- while (true) {
- int groupId = produceGroupId();
- BlockingQueue<Box> lane = lanes.get(groupId);
- lane.put(new Box(groupId));
- }
- } catch (InterruptedException ex) {
- Thread.currentThread().interrupt();
- }
- }
- int produceGroupId() {
- // generate random int between 1 and 3
- return ThreadLocalRandom.current().nextInt(1, 4);
- }
- }
- class Consumer implements Runnable {
- private final int consumerId;
- private final BlockingQueue<Box> lane;
- Consumer(int consumerId, BlockingQueue<Box> lane) {
- this.consumerId = consumerId;
- this.lane = lane;
- }
- public void run() {
- try {
- while (true) {
- consume(lane.take());
- }
- } catch (InterruptedException ex) {}
- }
- void consume(Box box) {
- System.out.println("Consumer " + consumerId + " received " + box + " for proxessing.");
- }
- }
Add Comment
Please, Sign In to add comment