Advertisement
add1ctus

Barber

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