Advertisement
Guest User

Untitled

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