Advertisement
NevaSayNo2Panda

OS Lab 3.3

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