Advertisement
crownedzero

Producer

Nov 15th, 2012
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package domain;
  6.  
  7. import java.util.ArrayList;
  8. import java.util.Date;
  9. import java.util.List;
  10.  
  11. /**
  12.  *
  13.  * @author crownedzero
  14.  */
  15. public class Producer implements Runnable {
  16.  
  17.     protected final static List<Message> sharedQueue = new ArrayList<>();
  18.     protected final int MAX_SIZE = 10;
  19.  
  20.     @Override
  21.     public void run() {
  22.         while (true) {
  23.             synchronized (sharedQueue) {
  24.                 while (sharedQueue.size() == MAX_SIZE) {
  25.                     try {
  26.                         sharedQueue.wait();
  27.                     } catch (InterruptedException e) {
  28.                     }
  29.                 }
  30.                 sharedQueue.add(new Message(Utility.getRandomProduct(), new Date(), Utility.regionLookup(Utility.getState())));
  31.                 System.out.println(Thread.currentThread().getName() + " adding. Queue size: " + sharedQueue.size());
  32.             }
  33.         }
  34.     }
  35.  
  36.     public static Message messageConsume(String region) {
  37.         synchronized(sharedQueue) {
  38.         while (sharedQueue.isEmpty()) {
  39.             try {
  40.                 sharedQueue.wait();
  41.             } catch (InterruptedException e) {
  42.             }
  43.         }
  44.         if (sharedQueue.get(0).getRegion().equalsIgnoreCase(region)) {
  45.             Message tempMessage = sharedQueue.get(0);
  46.             sharedQueue.remove(0);
  47.             return tempMessage;
  48.         } else {
  49.             return null;
  50.         }
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement