Advertisement
ilijakocev

berber

Mar 27th, 2015
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.52 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3. import java.util.HashSet;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.Random;
  7. import java.util.Scanner;
  8. import java.util.concurrent.Semaphore;
  9.  
  10. /**
  11.  *
  12.  * @author ristes
  13.  */
  14. public class TemplateNumRunsAndNumInstances {
  15.  
  16.     //TODO: definirajte gi semaforite i ostanatite promenlivi ovde (mora site da se static)
  17.    
  18.     static Semaphore client, berber, cDone, cReady, berberDone, vlezi;
  19.     final static Object lock = new Object();
  20.     static int br;
  21.    
  22.     public static void init(int numBarbers) {
  23.         client = new Semaphore(5);
  24.         berber = new Semaphore(0);
  25.         cDone = new Semaphore(0);
  26.         cReady = new Semaphore(0);
  27.         vlezi = new Semaphore(0);
  28.        
  29.        
  30.         berberDone = new Semaphore(0);
  31.        
  32.         br = 0;
  33.     }
  34.  
  35.     static class Barber extends TemplateThread {
  36.  
  37.         public int barberId;
  38.  
  39.         public Barber(int numRuns, int barberId) {
  40.             super(numRuns);
  41.             this.barberId = barberId;
  42.         }
  43.  
  44.         /**
  45.          * Da se implementira odnesuvanjeto na berberot spored baranjeto na
  46.          * zadacata.
  47.          *
  48.          *
  49.          * TODO: da se implementira
  50.          *
  51.          */
  52.         public void execute() throws InterruptedException {
  53.             berber.acquire();
  54.            
  55.             state.barberWakeUp();
  56.            
  57.             cReady.release();
  58.             state.barberCallCustomer();
  59.             vlezi.acquire();
  60.             state.cutHair();
  61.             cDone.release();
  62.            
  63.             berberDone.acquire();
  64.             state.barberGoToSleep();
  65.            
  66.         }
  67.     }
  68.  
  69.     static class Consumer extends TemplateThread {
  70.  
  71.         public Consumer(int numRuns) {
  72.             super(numRuns);
  73.         }
  74.  
  75.         /**
  76.          * Da se implementira odnesuvanjeto na ucesnikot spored uslovite na
  77.          * zadacata.
  78.          */
  79.         public void execute() throws InterruptedException {
  80.             client.acquire();
  81.             state.customerArrived();
  82.            
  83.             synchronized (lock)
  84.             {
  85.                 br++;
  86.                 if(br == 5)
  87.                 {
  88.                     berber.release();
  89.                 }
  90.             }
  91.            
  92.             cReady.acquire();
  93.            
  94.             state.customerEntry();
  95.             vlezi.release();
  96.             cDone.acquire();
  97.             state.customerPay();
  98.            
  99.            
  100.             synchronized (lock) {
  101.                 br--;
  102.                 if(br == 0)
  103.                 {
  104.                     berberDone.release();
  105.                 }
  106.             }
  107.            
  108.             client.release();
  109.            
  110.         }
  111.     }
  112.     //<editor-fold defaultstate="collapsed" desc="This is the template code" >
  113.     static State state;
  114.  
  115.     static class State {
  116.  
  117.         private static final Random RANDOM = new Random();
  118.         private static final int RANDOM_RANGE = 5;
  119.         private final int numBarbers;
  120.         private boolean barberWaked[];
  121.  
  122.         public State(int numBarbers) {
  123.             this.numBarbers = numBarbers;
  124.             barberWaked = new boolean[numBarbers];
  125.         }
  126.         private int arrivedCustomers = 0;
  127.         private int calledCustomers = 0;
  128.         private int maxCuttings = 0;
  129.         private int numCuttings = 0;
  130.  
  131.         public synchronized void customerArrived() throws RuntimeException {
  132.             log(null, "customer arrived");
  133.             arrivedCustomers++;
  134.         }
  135.  
  136.         public synchronized void barberWakeUp() throws RuntimeException {
  137.             Barber b = (Barber) Thread.currentThread();
  138.             if (barberWaked[b.barberId]) {
  139.                 PointsException e = new PointsException(5, "Berberot e veke buden i nema potreba da se razbudi.");
  140.                 log(e, null);
  141.             } else {
  142.                 log(null, "the barber is waked up");
  143.                 barberWaked[b.barberId] = true;
  144.             }
  145.         }
  146.  
  147.         public synchronized void barberCallCustomer() throws RuntimeException {
  148.             log(null, "the barber calls the customer");
  149.             if (arrivedCustomers <= 0) {
  150.                 PointsException e = new PointsException(5, "Brojot na klienti koi cekaat e 0 i nema koj da bide povikan.");
  151.                 log(e, null);
  152.             }
  153.             calledCustomers++;
  154.         }
  155.  
  156.         public synchronized void customerEntry() throws RuntimeException {
  157.             log(null, "customer sits in the chair");
  158.             if (arrivedCustomers <= 0) {
  159.                 PointsException e = new PointsException(5, "Brojot na klienti koi cekaat e 0 i nema koj da vleze.");
  160.                 log(e, null);
  161.             }
  162.             if (calledCustomers <= 0) {
  163.                 PointsException e = new PointsException(5, "Nema povikano klient i ne moze da vleze.");
  164.                 log(e, null);
  165.             }
  166.             arrivedCustomers--;
  167.             calledCustomers--;
  168.  
  169.             numCuttings++;
  170.         }
  171.  
  172.         public void cutHair() throws RuntimeException {
  173.             synchronized (this) {
  174.                 if (numCuttings <= 0) {
  175.                     PointsException e = new PointsException(5, "Nema prisuten klient za potstrizuvanje");
  176.                     log(e, null);
  177.                 }
  178.  
  179.                 log(null, "berber cuts the customer hair");
  180.             }
  181.             try {
  182.                 int r;
  183.                 synchronized (this) {
  184.                     r = RANDOM.nextInt(RANDOM_RANGE);
  185.                 }
  186.                 Thread.sleep(r);
  187.             } catch (Exception e) {
  188.                 //do nothing
  189.             }
  190.             synchronized (this) {
  191.                 if (numCuttings <= 0) {
  192.                     PointsException e = new PointsException(5, "Brojot na klienti koi se strizat e 0 i nema koj da izleze.");
  193.                     log(e, null);
  194.                 }
  195.                 numCuttings--;
  196.             }
  197.  
  198.         }
  199.  
  200.         public synchronized void customerPay() throws RuntimeException {
  201.             log(null, "customer is paying and leaving the shop");
  202.  
  203.  
  204.         }
  205.  
  206.         public synchronized void barberGoToSleep() throws RuntimeException {
  207.             Barber b = (Barber) Thread.currentThread();
  208.             if (!barberWaked[b.barberId]) {
  209.                 PointsException e = new PointsException(5, "Berberite veke spijat i ne moze da se prezaspijat.");
  210.                 log(e, null);
  211.             }
  212.             if (arrivedCustomers > 0) {
  213.                 PointsException e = new PointsException(5, "Seuste ima klienti koi cekaat i berberot ne moze da odi na spienje.");
  214.                 log(e, null);
  215.             }
  216.             log(null, "all barbers go to sleap");
  217.             barberWaked[b.barberId] = false;
  218.         }
  219.         private List<String> actions = new ArrayList<String>();
  220.         private List<PointsException> exceptions = new ArrayList<PointsException>();
  221.  
  222.         private synchronized void log(PointsException e, String action) {
  223.             TemplateThread t = (TemplateThread) Thread.currentThread();
  224.             if (e == null) {
  225.                 actions.add(t.toString() + "\t(a): " + action);
  226.             } else {
  227.                 t.setException(e);
  228.                 actions.add(t.toString() + "\t(e): " + e.getMessage());
  229.             }
  230.         }
  231.  
  232.         public synchronized void printLog() {
  233.             System.out.println("Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
  234.             System.out.println("Log na izvrsuvanje na akciite:");
  235.             System.out.println("=========================");
  236.             System.out.println("tip\tid\titer\takcija/error");
  237.             System.out.println("=========================");
  238.             for (String l : actions) {
  239.                 System.out.println(l);
  240.             }
  241.         }
  242.  
  243.         public void printStatus() {
  244.             if (!TemplateThread.hasException) {
  245.                 int poeni = 25;
  246.                 if (PointsException.getTotalPoints() == 0) {
  247.                     System.out.println("Procesot e uspesno sinhroniziran. Osvoeni 25 poeni.");
  248.                 } else {
  249.                     poeni -= PointsException.getTotalPoints();
  250.                     PointsException.printErrors();
  251.                     System.out.println("Osvoeni poeni: " + poeni);
  252.                 }
  253.  
  254.             } else {
  255.                 System.out.println("Procesot ne e sinhroniziran spored uslovite na zadacata");
  256.                 printLog();
  257.                 System.out.println("====================================================");
  258.                 PointsException.printErrors();
  259.                 System.out.println("Maksimum Poeni: " + (25 - PointsException.getTotalPoints()));
  260.             }
  261.  
  262.         }
  263.     }
  264.  
  265.     abstract static class TemplateThread extends Thread {
  266.  
  267.         static boolean hasException = false;
  268.         int numRuns = 1;
  269.         public int iteration = 0;
  270.         private Exception exception = null;
  271.  
  272.         public TemplateThread(int numRuns) {
  273.             this.numRuns = numRuns;
  274.         }
  275.  
  276.         abstract void execute() throws InterruptedException;
  277.  
  278.         @Override
  279.         public void run() {
  280.             try {
  281.                 for (int i = 0; i < numRuns && !hasException; i++) {
  282.                     execute();
  283.                     iteration++;
  284.  
  285.                 }
  286.             } catch (InterruptedException e) {
  287.                 // Do nothing
  288.             } catch (Exception e) {
  289.                 exception = e;
  290.                 hasException = true;
  291.             }
  292.         }
  293.  
  294.         public void setException(Exception exception) {
  295.             this.exception = exception;
  296.             hasException = true;
  297.         }
  298.  
  299.         @Override
  300.         public String toString() {
  301.             Thread current = Thread.currentThread();
  302.             if (numRuns > 1) {
  303.                 return String.format("%s\t%d\t%d", "" + current.getClass().getSimpleName().charAt(0), getId(), iteration);
  304.             } else {
  305.                 return String.format("%s\t%d\t", "" + current.getClass().getSimpleName().charAt(0), getId());
  306.             }
  307.         }
  308.     }
  309.  
  310.     static class PointsException extends RuntimeException {
  311.  
  312.         private static HashMap<String, PointsException> exceptions = new HashMap<String, PointsException>();
  313.         private int points;
  314.  
  315.         public PointsException(int points, String message) {
  316.             super(message);
  317.             this.points = points;
  318.             exceptions.put(message, this);
  319.         }
  320.  
  321.         public static int getTotalPoints() {
  322.             int sum = 0;
  323.             for (PointsException e : exceptions.values()) {
  324.                 sum += e.getPoints();
  325.             }
  326.             return sum;
  327.         }
  328.  
  329.         public static void printErrors() {
  330.             System.out.println("Gi imate slednite greski: ");
  331.             for (Map.Entry<String, PointsException> e : exceptions.entrySet()) {
  332.                 System.out.println(String.format("[%s] : (-%d)", e.getKey(), e.getValue().getPoints()));
  333.             }
  334.         }
  335.  
  336.         public int getPoints() {
  337.             return points;
  338.         }
  339.     }
  340.  
  341.     public static void main(String[] args) {
  342.         try {
  343.             start();
  344.         } catch (Exception ex) {
  345.             ex.printStackTrace();
  346.         }
  347.     }
  348.  
  349.     public static void start() throws Exception {
  350.         Scanner s = new Scanner(System.in);
  351.         int brBarbers = s.nextInt();
  352.         int brKonzumeri = s.nextInt();
  353.         int numBarberRuns = s.nextInt();
  354.         int numCustomerRuns = s.nextInt();
  355.         init(brBarbers);
  356.  
  357.         state = new State(brBarbers);
  358.         HashSet<Thread> threads = new HashSet<Thread>();
  359.  
  360.         for (int i = 0; i < brBarbers; i++) {
  361.             Barber prod = new Barber(numBarberRuns, i);
  362.             threads.add(prod);
  363.             prod.start();
  364.             Consumer c = new Consumer(numCustomerRuns);
  365.             threads.add(c);
  366.             c.start();
  367.         }
  368.  
  369.         for (int i = 0; i < brKonzumeri / 2 - brBarbers; i++) {
  370.             Consumer c = new Consumer(numCustomerRuns);
  371.             threads.add(c);
  372.             c.start();
  373.         }
  374.         try {
  375.             Thread.sleep(50);
  376.         } catch (Exception e) {
  377.             //do nothing
  378.         }
  379.         for (int i = 0; i < brKonzumeri / 2; i++) {
  380.             Consumer c = new Consumer(numCustomerRuns);
  381.             threads.add(c);
  382.             c.start();
  383.         }
  384.  
  385.  
  386.         for (Thread t : threads) {
  387.             t.join(1000);
  388.         }
  389.  
  390.         for (Thread t : threads) {
  391.             if (t.isAlive()) {
  392.                 t.interrupt();
  393.             }
  394.         }
  395.  
  396.         state.printStatus();
  397.     }
  398.     //</editor-fold>
  399. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement