Advertisement
nocturnalmk

Untitled

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