Advertisement
NebojshaTodorovic

Оперативни Системи-ЛАБ3- Заспаниот бербер

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