Crazy

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

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