Advertisement
Azure47

OS Lab 3.3

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