Guest User

Untitled

a guest
Feb 16th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.concurrent.*;
  3.  
  4. class LanesAndBoxesAnswer {
  5. public static void main(String[] args) {
  6. BlockingQueue<Box> lane1 = new LinkedBlockingQueue<Box>();
  7. BlockingQueue<Box> lane2 = new LinkedBlockingQueue<Box>();
  8. BlockingQueue<Box> lane3 = new LinkedBlockingQueue<Box>();
  9. Map<Integer, BlockingQueue<Box>> lanes = new ConcurrentHashMap<Integer, BlockingQueue<Box>>();
  10. lanes.put(1, lane1);
  11. lanes.put(2, lane2);
  12. lanes.put(3, lane3);
  13.  
  14. Producer p = new Producer(lanes);
  15. Consumer c1 = new Consumer(1, lane1);
  16. Consumer c2 = new Consumer(2, lane2);
  17. Consumer c3 = new Consumer(3, lane3);
  18.  
  19. new Thread(p).start();
  20. new Thread(c1).start();
  21. new Thread(c2).start();
  22. new Thread(c3).start();
  23. }
  24. }
  25.  
  26. class Box {
  27. private final int groupId;
  28. public Box(int groupId) {
  29. this.groupId = groupId;
  30. }
  31. @Override
  32. public String toString() {
  33. return "<Box " + groupId + ">";
  34. }
  35. }
  36.  
  37. class Producer implements Runnable {
  38. private final Map<Integer, BlockingQueue<Box>> lanes;
  39. Producer(Map<Integer, BlockingQueue<Box>> lanes) {
  40. this.lanes = lanes;
  41. }
  42. public void run() {
  43. try {
  44. while (true) {
  45. int groupId = produceGroupId();
  46. BlockingQueue<Box> lane = lanes.get(groupId);
  47. lane.put(new Box(groupId));
  48. }
  49. } catch (InterruptedException ex) {
  50. Thread.currentThread().interrupt();
  51. }
  52. }
  53. int produceGroupId() {
  54. // generate random int between 1 and 3
  55. return ThreadLocalRandom.current().nextInt(1, 4);
  56. }
  57. }
  58.  
  59. class Consumer implements Runnable {
  60. private final int consumerId;
  61. private final BlockingQueue<Box> lane;
  62. Consumer(int consumerId, BlockingQueue<Box> lane) {
  63. this.consumerId = consumerId;
  64. this.lane = lane;
  65. }
  66. public void run() {
  67. try {
  68. while (true) {
  69. consume(lane.take());
  70. }
  71. } catch (InterruptedException ex) {}
  72. }
  73. void consume(Box box) {
  74. System.out.println("Consumer " + consumerId + " received " + box + " for proxessing.");
  75. }
  76. }
Add Comment
Please, Sign In to add comment