Advertisement
Azure47

OS Lab 3.2

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