Crazy

Заспаниот бербер

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