Advertisement
Guest User

Untitled

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