Advertisement
Latkoski

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

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