Advertisement
salercode

OS lab3zad2

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