Advertisement
LonelyShepherd

Заспаниот бербер [Лаб. 3.2]

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