Advertisement
ilevishinov

Племенска Вечера

Mar 19th, 2018
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.75 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. import java.util.concurrent.atomic.AtomicInteger;
  10.  
  11. /**
  12.  *
  13.  * @author ristes
  14.  */
  15. public class TribeDinner {
  16.  
  17.     // TODO: definirajte gi semaforite i ostanatite promenlivi ovde (mora site
  18.     // da se static)
  19.    
  20.    
  21.     public static Semaphore fillPlate;
  22.     public static Semaphore check;
  23.    
  24.     /**
  25.      * Metod koj treba da gi inicijalizira vrednostite na semaforite i
  26.      * ostanatite promenlivi za sinhronizacija.
  27.      *
  28.      *
  29.      * TODO: da se implementira
  30.      *
  31.      */
  32.    
  33.    
  34.    
  35.     public static void init(int numBarbers) {
  36.         fillPlate = new Semaphore(3);
  37.         check = new Semaphore(1);
  38.     }
  39.  
  40.     static class TribeMember extends TemplateThread {
  41.  
  42.         public TribeMember(int numRuns) {
  43.             super(numRuns);
  44.         }
  45.  
  46.         /**
  47.          * Da se implementira odnesuvanjeto na ucesnikot spored uslovite na
  48.          * zadacata.
  49.          */
  50.         public void execute() throws InterruptedException {
  51.             // nesinhronizirano scenario
  52. //          if (!state.isPotEmpty()) {
  53. //              state.fillPlate();
  54. //              state.eat();
  55. //          } else {
  56. //              state.cook();
  57. //          }
  58.            
  59.             check.acquire();
  60.             if(state.isPotEmpty()) {
  61.                 state.cook();
  62.             }
  63.             check.release();
  64.            
  65.             fillPlate.acquire();
  66.             state.fillPlate();
  67.             fillPlate.release();
  68.             state.eat();
  69.         }
  70.     }
  71.  
  72.     // <editor-fold defaultstate="collapsed" desc="This is the template code" >
  73.     static State state;
  74.  
  75.     static class State {
  76.  
  77.         private static final String _10_JADENJETO_NE_E_PARALELIZIRANO = "jadenjeto ne e paralelizirano. Site jadat eden po eden";
  78.         private static final String _10_PRISTAPOT_DO_KAZANOT_NE_E_PARALELIZIRAN = "Pristapot do kazanot ne e paraleliziran. Treda da moze do trojca paralelno da zemaat hrana.";
  79.  
  80.         private static final String _10_DVAJCA_ISTOVREMENO_PROVERUVAAT = "Dvajca istovremeno proveruvaat dali kazanot e prazen. Maksimum eden e dozvoleno.";
  81.         private static final String _7_NEMA_MESTO_POKRAJ_KAZANOT = "Nema mesto pokraj kazanot. Maksimum tri clena moze da zemaat hrana istovremeno.";
  82.         private static final String _5_NE_MOZE_DA_JADE_OD_PRAZEN_KAZAN = "Ne moze da jade od prazen kazan. Treba da se povika 'state.cook()'";
  83.         private static final String _5_NE_MOZE_DA_SE_GOTVI_VO_KAZAN_KOJ_NE_E_PRAZEN = "Ne moze da se gotvi vo kazan koj ne e prazen";
  84.  
  85.         private static final Random RANDOM = new Random();
  86.         private static final int POT_CAPACITY = 15;
  87.  
  88.         private LimitedCounter platesLeft = new LimitedCounter(0, null, 0,
  89.                 null, 0, 5, _5_NE_MOZE_DA_JADE_OD_PRAZEN_KAZAN);
  90.  
  91.         private LimitedCounter checks = new LimitedCounter(0, 1, 10,
  92.                 _10_DVAJCA_ISTOVREMENO_PROVERUVAAT, null, 0, null);
  93.  
  94.         private LimitedCounter fills = new LimitedCounter(0, 3, 7,
  95.                 _7_NEMA_MESTO_POKRAJ_KAZANOT, null, 0, null);
  96.  
  97.         private LimitedCounter eat = new LimitedCounter(0);
  98.  
  99.         public State() {
  100.  
  101.         }
  102.  
  103.         public boolean isPotEmpty() throws RuntimeException {
  104.             log(checks.incrementWithMax(), "proverka dali ima hrana vo kazanot");
  105.             sleep(5);
  106.             boolean res = platesLeft.getValue() == 0;
  107.             log(checks.decrementWithMin(), null);
  108.             return res;
  109.         }
  110.  
  111.         public void fillPlate() throws RuntimeException {
  112.             log(fills.incrementWithMax(), "zemanje na hrana");
  113.             log(platesLeft.decrementWithMin(), null);
  114.             sleep(5);
  115.             log(platesLeft.incrementWithMax(), null);
  116.             log(fills.decrementWithMin(), null);
  117.         }
  118.  
  119.         public void eat() throws RuntimeException {
  120.             log(eat.incrementWithMax(), "jadenje");
  121.             sleep(10);
  122.             log(eat.decrementWithMin(), null);
  123.         }
  124.  
  125.         public void cook() throws RuntimeException {
  126.             synchronized (State.class) {
  127.                 if (platesLeft.getValue() == 0) {
  128.                     platesLeft.setValue(POT_CAPACITY);
  129.                 } else {
  130.                     PointsException e = new PointsException(5,
  131.                             _5_NE_MOZE_DA_SE_GOTVI_VO_KAZAN_KOJ_NE_E_PRAZEN);
  132.                     log(e, null);
  133.                 }
  134.             }
  135.         }
  136.  
  137.         public void finalize() {
  138.             if (fills.getMax() == 1) {
  139.                 logException(new PointsException(10,
  140.                         _10_PRISTAPOT_DO_KAZANOT_NE_E_PARALELIZIRAN));
  141.             }
  142.             if (eat.getMax() == 1) {
  143.                 logException(new PointsException(10,
  144.                         _10_JADENJETO_NE_E_PARALELIZIRANO));
  145.             }
  146.         }
  147.  
  148.         private List<String> actions = new ArrayList<String>();
  149.  
  150.         private void sleep(int range) {
  151.             try {
  152.                 Thread.sleep(RANDOM.nextInt(range));
  153.             } catch (InterruptedException e) {
  154.             }
  155.         }
  156.  
  157.         protected TemplateThread getThread() {
  158.             TemplateThread t = (TemplateThread) Thread.currentThread();
  159.             return t;
  160.         }
  161.  
  162.         private synchronized void log(PointsException e, String action) {
  163.             TemplateThread t = (TemplateThread) Thread.currentThread();
  164.             if (e != null) {
  165.                 t.setException(e);
  166.                 actions.add(t.toString() + "\t(e): " + e.getMessage());
  167.             } else if (action != null) {
  168.                 actions.add(t.toString() + "\t(a): " + action);
  169.             }
  170.         }
  171.  
  172.         private synchronized void logException(PointsException e) {
  173.             actions.add("\t(e): " + e.getMessage());
  174.         }
  175.  
  176.         public synchronized void printLog() {
  177.             System.out
  178.                     .println("Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
  179.             System.out.println("Log na izvrsuvanje na akciite:");
  180.             System.out.println("=========================");
  181.             System.out.println("tip\tid\titer\takcija/error");
  182.             System.out.println("=========================");
  183.             for (String l : actions) {
  184.                 System.out.println(l);
  185.             }
  186.         }
  187.  
  188.         public void printStatus() {
  189.             finalize();
  190.             if (!TemplateThread.hasException) {
  191.                 int poeni = 25;
  192.                 if (PointsException.getTotalPoints() == 0) {
  193.                     System.out
  194.                             .println("Procesot e uspesno sinhroniziran. Osvoeni 25 poeni.");
  195.                 } else {
  196.                     poeni -= PointsException.getTotalPoints();
  197.                     PointsException.printErrors();
  198.                     System.out.println("Maksimalni osvoeni poeni: " + poeni);
  199.                 }
  200.  
  201.             } else {
  202.                 System.out
  203.                         .println("Procesot ne e sinhroniziran spored uslovite na zadacata");
  204.                 printLog();
  205.                 System.out
  206.                         .println("====================================================");
  207.                 PointsException.printErrors();
  208.                 int total = (25 - PointsException.getTotalPoints());
  209.                 if (total < 0) {
  210.                     total = 0;
  211.                 }
  212.                 System.out.println("Maksimum Poeni: " + total);
  213.             }
  214.  
  215.         }
  216.     }
  217.  
  218.     static class LimitedCounter {
  219.  
  220.         private int value;
  221.         private Integer maxAllowed;
  222.         private Integer minAllowed;
  223.         private int maxErrorPoints;
  224.         private int minErrorPoints;
  225.         private String maxErrorMessage;
  226.         private String minErrorMessage;
  227.  
  228.         private int max;
  229.  
  230.         public LimitedCounter(int value) {
  231.             super();
  232.             this.value = value;
  233.             this.max = value;
  234.         }
  235.  
  236.         public LimitedCounter(int value, Integer maxAllowed,
  237.                 int maxErrorPoints, String maxErrorMessage, Integer minAllowed,
  238.                 int minErrorPoints, String minErrorMessage) {
  239.             super();
  240.             this.value = value;
  241.             this.max = value;
  242.             this.maxAllowed = maxAllowed;
  243.             this.minAllowed = minAllowed;
  244.             this.maxErrorPoints = maxErrorPoints;
  245.             this.minErrorPoints = minErrorPoints;
  246.             this.maxErrorMessage = maxErrorMessage;
  247.             this.minErrorMessage = minErrorMessage;
  248.         }
  249.  
  250.         public int getMax() {
  251.             return max;
  252.         }
  253.  
  254.         public int getValue() {
  255.             return value;
  256.         }
  257.  
  258.         public void setValue(int value) {
  259.             this.value = value;
  260.         }
  261.  
  262.         public PointsException incrementWithMax() {
  263.             synchronized (LimitedCounter.class) {
  264.                 value++;
  265.                 if (value > max) {
  266.                     max = value;
  267.                 }
  268.                 if (maxAllowed != null) {
  269.                     if (value > maxAllowed) {
  270.                         PointsException e = new PointsException(maxErrorPoints,
  271.                                 maxErrorMessage);
  272.                         return e;
  273.                     }
  274.                 }
  275.             }
  276.             return null;
  277.         }
  278.  
  279.         public PointsException decrementWithMin() {
  280.             synchronized (LimitedCounter.class) {
  281.                 value--;
  282.                 if (minAllowed != null) {
  283.                     if (value < minAllowed) {
  284.                         PointsException e = new PointsException(minErrorPoints,
  285.                                 minErrorMessage);
  286.                         return e;
  287.                     }
  288.                 }
  289.             }
  290.             return null;
  291.         }
  292.     }
  293.  
  294.     abstract static class TemplateThread extends Thread {
  295.  
  296.         static boolean hasException = false;
  297.         int numRuns = 1;
  298.         public int iteration = 0;
  299.         protected Exception exception = null;
  300.  
  301.         public TemplateThread(int numRuns) {
  302.             this.numRuns = numRuns;
  303.         }
  304.  
  305.         abstract void execute() throws InterruptedException;
  306.  
  307.         @Override
  308.         public void run() {
  309.             try {
  310.                 for (int i = 0; i < numRuns && !hasException; i++) {
  311.                     execute();
  312.                     iteration++;
  313.  
  314.                 }
  315.             } catch (InterruptedException e) {
  316.                 // Do nothing
  317.             } catch (Exception e) {
  318.                 exception = e;
  319.                 hasException = true;
  320.             }
  321.         }
  322.  
  323.         public void setException(Exception exception) {
  324.             this.exception = exception;
  325.             hasException = true;
  326.         }
  327.  
  328.         @Override
  329.         public String toString() {
  330.             Thread current = Thread.currentThread();
  331.             if (numRuns > 1) {
  332.                 return String.format("%s\t%d\t%d", ""
  333.                         + current.getClass().getSimpleName().charAt(0),
  334.                         getId(), iteration);
  335.             } else {
  336.                 return String
  337.                         .format("%s\t%d\t", ""
  338.                                 + current.getClass().getSimpleName().charAt(0),
  339.                                 getId());
  340.             }
  341.         }
  342.     }
  343.  
  344.     static class PointsException extends RuntimeException {
  345.  
  346.         private static HashMap<String, PointsException> exceptions = new HashMap<String, PointsException>();
  347.         private int points;
  348.  
  349.         public PointsException(int points, String message) {
  350.             super(message);
  351.             this.points = points;
  352.             exceptions.put(message, this);
  353.         }
  354.  
  355.         public static int getTotalPoints() {
  356.             int sum = 0;
  357.             for (PointsException e : exceptions.values()) {
  358.                 sum += e.getPoints();
  359.             }
  360.             return sum;
  361.         }
  362.  
  363.         public static void printErrors() {
  364.             System.out.println("Gi imate slednite greski: ");
  365.             for (Map.Entry<String, PointsException> e : exceptions.entrySet()) {
  366.                 System.out.println(String.format("[%s] : (-%d)", e.getKey(), e
  367.                         .getValue().getPoints()));
  368.             }
  369.         }
  370.  
  371.         public int getPoints() {
  372.             return points;
  373.         }
  374.     }
  375.  
  376.     public static void main(String[] args) {
  377.         try {
  378.             start();
  379.         } catch (Exception ex) {
  380.             ex.printStackTrace();
  381.         }
  382.     }
  383.  
  384.     public static void start() throws Exception {
  385.         Scanner s = new Scanner(System.in);
  386.         int brKonzumeri = s.nextInt();
  387.         int numCustomerRuns = s.nextInt();
  388.         init(brKonzumeri);
  389.  
  390.         state = new State();
  391.         HashSet<Thread> threads = new HashSet<Thread>();
  392.  
  393.         for (int i = 0; i < brKonzumeri; i++) {
  394.             TribeMember c = new TribeMember(numCustomerRuns);
  395.             threads.add(c);
  396.             c.start();
  397.         }
  398.         try {
  399.             Thread.sleep(50);
  400.         } catch (Exception e) {
  401.             // do nothing
  402.         }
  403.  
  404.         for (Thread t : threads) {
  405.             t.join(1000);
  406.         }
  407.  
  408.         for (Thread t : threads) {
  409.             if (t.isAlive()) {
  410.                 t.interrupt();
  411.                 if (t instanceof TemplateThread) {
  412.                     TemplateThread tt = (TemplateThread) t;
  413.                     tt.setException(new PointsException(25, "DEADLOCK"));
  414.                 }
  415.             }
  416.         }
  417.         s.close();
  418.         state.printStatus();
  419.     }
  420.     // </editor-fold>
  421. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement