ZivkicaI

SushiBar

Mar 16th, 2017
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1. package mk.ukim.finki.os.synchronization.exam15.march.sushibar;
  2.  
  3. import mk.ukim.finki.os.synchronization.ProblemExecution;
  4. import mk.ukim.finki.os.synchronization.TemplateThread;
  5.  
  6. import java.util.HashSet;
  7. import java.util.concurrent.Semaphore;
  8.  
  9. public class SushiBarSolution {
  10.  public static Semaphore vlez=new Semaphore(6);
  11.  public static Semaphore cekaj=new Semaphore(0);
  12.  public static int lugje=0;
  13.  
  14.  
  15.  
  16.     public static void init() {
  17.     }
  18.  
  19.     public static class Customer extends TemplateThread {
  20.  
  21.         public Customer(int numRuns) {
  22.             super(numRuns);
  23.         }
  24.  
  25.         @Override
  26.         public void execute() throws InterruptedException {
  27.         vlez.acquire();
  28.         state.customerSeat();
  29.         synchronized (state)
  30.         {
  31.             lugje++;
  32.             if(lugje==6)
  33.             {
  34.                 state.callWaiter();
  35.                 cekaj.release(6);
  36.             }
  37.         }
  38.         cekaj.acquire();
  39.         state.customerEat();
  40.         synchronized(state)
  41.         {
  42.             lugje--;
  43.             if(lugje==0)
  44.             {
  45.                 state.eatingDone();
  46.                 vlez.release(6);
  47.             }
  48.         }
  49.    
  50.        
  51.        
  52.         }
  53.     }
  54.  
  55.     public static void main(String[] args) {
  56.         for (int i = 0; i < 10; i++) {
  57.             run();
  58.         }
  59.     }
  60.  
  61.     static SushiBarState state = new SushiBarState();
  62.  
  63.     public static void run() {
  64.         try {
  65.             int numRuns = 1;
  66.             int numIterations = 1200;
  67.  
  68.             HashSet<Thread> threads = new HashSet<Thread>();
  69.  
  70.             for (int i = 0; i < numIterations; i++) {
  71.                 Customer c = new Customer(numRuns);
  72.                 threads.add(c);
  73.             }
  74.  
  75.             init();
  76.  
  77.             ProblemExecution.start(threads, state);
  78.             // System.out.println(new Date().getTime());
  79.         } catch (Exception ex) {
  80.             ex.printStackTrace();
  81.         }
  82.     }
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment