Advertisement
salercode

DopolnitelnaMuzickiBend

Mar 24th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.73 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Date;
  3. import java.util.HashMap;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.Random;
  8. import java.util.Scanner;
  9. import java.util.concurrent.Semaphore;
  10.  
  11. public class MusicBand {
  12.  
  13.  
  14.     static MusicBandState state = new MusicBandState();
  15.     //TODO: Definicija na globalni promenlivi i semafori
  16.     static Semaphore pejaci;
  17.     static Semaphore gitaristi;
  18.     static Semaphore lock;
  19.     static Semaphore pejacHere;
  20.     static Semaphore gitaristHere;
  21.     static Semaphore posledenKluc;
  22.     public static void init() {
  23.         //TODO: da se implementira
  24.         pejaci=new Semaphore(2);
  25.         gitaristi=new Semaphore (3);
  26.         lock=new Semaphore(1);
  27.         pejacHere=new Semaphore(0);
  28.         gitaristHere=new Semaphore(0);
  29.         posledenKluc=new Semaphore(1);
  30.     }
  31.  
  32.     public static class GuitarPlayer extends TemplateThread {
  33.         int brojGitaristi=0;
  34.  
  35.         public GuitarPlayer(int numRuns) {
  36.             super(numRuns);
  37.         }
  38.  
  39.         @Override
  40.         public void execute() throws InterruptedException {
  41.             //TODO: da se implementira
  42.             lock.acquire();
  43.             brojGitaristi++;
  44.  
  45.             gitaristHere.release();
  46.             if(brojGitaristi==3)
  47.             {
  48.                 gitaristi.acquire();
  49.                 gitaristHere.acquire();
  50.                 state.play();
  51.  
  52.             }
  53.  
  54.             gitaristi.release();
  55.             lock.release();
  56.  
  57.             posledenKluc.acquire();
  58.             state.evaluate();
  59.             posledenKluc.release();
  60.         }
  61.  
  62.     }
  63.  
  64.     public static class Singer extends TemplateThread {
  65.         int pejaci=0;
  66.         public Singer(int numRuns) {
  67.             super(numRuns);
  68.         }
  69.  
  70.         @Override
  71.         public void execute() throws InterruptedException {
  72.             //TODO: da se implementira
  73.             lock.release();
  74.  
  75.             pejaci++;
  76.  
  77.             pejacHere.release();
  78.  
  79.  
  80.             if(pejaci==2)
  81.             {
  82.                 gitaristi.acquire();
  83.                 pejacHere.acquire();
  84.                 state.play();
  85.                 gitaristi.release();
  86.             }
  87.  
  88.             lock.release();
  89.             posledenKluc.acquire();
  90.             state.evaluate();
  91.             posledenKluc.release();
  92.         }
  93.  
  94.     }
  95.  
  96.     public static void main(String[] args) {
  97.         for (int i = 0; i < 10; i++) {
  98.             run();
  99.         }
  100.     }
  101.  
  102.     public static void run() {
  103.         try {
  104.             Scanner s = new Scanner(System.in);
  105.             int numRuns = 1;
  106.             int numIterations = 100;
  107.             s.close();
  108.  
  109.             HashSet<Thread> threads = new HashSet<Thread>();
  110.  
  111.             for (int i = 0; i < numIterations; i++) {
  112.                 Singer singer = new Singer(numRuns);
  113.                 threads.add(singer);
  114.                 GuitarPlayer gp = new GuitarPlayer(numRuns);
  115.                 threads.add(gp);
  116.                 gp = new GuitarPlayer(numRuns);
  117.                 threads.add(gp);
  118.                 singer = new Singer(numRuns);
  119.                 threads.add(singer);
  120.                 gp = new GuitarPlayer(numRuns);
  121.                 threads.add(gp);
  122.             }
  123.  
  124.             init();
  125.  
  126.             ProblemExecution.start(threads, state);
  127.             //System.out.println(new Date().getTime());
  128.         } catch (Exception ex) {
  129.             ex.printStackTrace();
  130.         }
  131.     }
  132.  
  133. }
  134. class MusicBandState extends AbstractState {
  135.  
  136.     private static final String PLAYING_NOT_PARALLEL = "The playing is not in parallel!";
  137.     private static final String GROUP_NOT_FORMED = "The previous group is not formed";
  138.     private static final String MAXIMUM_3_GUITAR_PLAYERS = "Maximum 3 Guitar Players playing is allowed.";
  139.     private static final String MAXIMUM_2_SINGER = "Maximum 2 Singers playing is allowed.";
  140.     private static final int MAXIMUM_2_SINGER_POINTS = 5;
  141.     private static final int MAXIMUM_3_GUITAR_PLAYERS_POINTS = 5;
  142.     private static final int GROUP_NOT_FORMED_POINTS = 5;
  143.     private static final int PLAYING_NOT_PARALLEL_POINTS = 5;
  144.  
  145.     int groupMembersCount = 0;
  146.     private BoundCounterWithRaceConditionCheck guitarPlayer;
  147.     private BoundCounterWithRaceConditionCheck singer;
  148.  
  149.     public MusicBandState() {
  150.         guitarPlayer = new BoundCounterWithRaceConditionCheck(0, 3,
  151.                 MAXIMUM_3_GUITAR_PLAYERS_POINTS, MAXIMUM_3_GUITAR_PLAYERS, null, 0, null);
  152.         singer = new BoundCounterWithRaceConditionCheck(0, 2,
  153.                 MAXIMUM_2_SINGER_POINTS, MAXIMUM_2_SINGER, null, 0, null);
  154.     }
  155.  
  156.     public void play() {
  157.         synchronized (this) {
  158.             groupMembersCount++;
  159.         }
  160.         if (getThread() instanceof MusicBand.GuitarPlayer) {
  161.             log(guitarPlayer.incrementWithMax(false), "Guitar Player is playing");
  162.         } else if (getThread() instanceof MusicBand.Singer) {
  163.             log(singer.incrementWithMax(false), "Singer is playing");
  164.         }
  165.         Switcher.forceSwitch(3);
  166.         if(guitarPlayer.getValue()!=3 || singer.getValue()!=2 ) {
  167. //        log(new PointsException(5,"Ne se prisutni site"),"");
  168.         }
  169.  
  170.     }
  171.  
  172.     public void evaluate() {
  173.         synchronized (this) {
  174.             if (groupMembersCount == 5) {
  175.                 if (guitarPlayer.getValue() == 3&&singer.getValue() == 2) {
  176.                     reset();
  177.                     log(null, "The group has performed.");
  178.                 } else {
  179.                     log(new PointsException(
  180.                             GROUP_NOT_FORMED_POINTS,
  181.                             GROUP_NOT_FORMED), null);
  182.  
  183.                 }
  184.             }
  185.         }
  186.     }
  187.  
  188.     private synchronized void reset() {
  189.         guitarPlayer.setValue(0);
  190.         singer.setValue(0);
  191.         groupMembersCount = 0;
  192.     }
  193.  
  194.     @Override
  195.     public synchronized void finalize() {
  196.         if (guitarPlayer.getMax() == 1&&singer.getMax() == 1) {
  197.             logException(new PointsException(PLAYING_NOT_PARALLEL_POINTS,
  198.                     PLAYING_NOT_PARALLEL));
  199.         }
  200.     }
  201.  
  202. }
  203.  
  204. abstract class AbstractState {
  205.  
  206.     /**
  207.      * Method called after threads ended their execution to validate the
  208.      * correctness of the scenario
  209.      */
  210.     public abstract void finalize();
  211.  
  212.     /**
  213.      * List of logged actions
  214.      */
  215.     private List<String> actions = new ArrayList<String>();
  216.  
  217.     /**
  218.      *
  219.      * @return if the current thread is instance of TemplateThread it is
  220.      *         returned, and otherwise null is returned
  221.      */
  222.     protected TemplateThread getThread() {
  223.         Thread current = Thread.currentThread();
  224.         if (current instanceof TemplateThread) {
  225.             TemplateThread t = (TemplateThread) current;
  226.             return t;
  227.         } else {
  228.             return null;
  229.         }
  230.     }
  231.  
  232.     /**
  233.      * Log this exception or action
  234.      *
  235.      * @param e
  236.      *            occurred exception (null if no exception)
  237.      * @param action
  238.      *            Description of the occurring action
  239.      */
  240.     public synchronized void log(PointsException e, String action) {
  241.         TemplateThread t = (TemplateThread) Thread.currentThread();
  242.         if (e != null) {
  243.             t.setException(e);
  244.             actions.add(t.toString() + "\t(e): " + e.getMessage());
  245.         } else if (action != null) {
  246.             actions.add(t.toString() + "\t(a): " + action);
  247.         }
  248.     }
  249.  
  250.     /**
  251.      * Logging exceptions
  252.      *
  253.      * @param e
  254.      */
  255.     protected synchronized void logException(PointsException e) {
  256.         Thread t = Thread.currentThread();
  257.         if (e != null) {
  258.             if (t instanceof TemplateThread) {
  259.                 ((TemplateThread) t).setException(e);
  260.             }
  261.             TemplateThread.hasException=true;
  262.             actions.add("\t(e): " + e.getMessage());
  263.         }
  264.     }
  265.  
  266.     /**
  267.      * Printing of the actions and exceptions that has occurred
  268.      */
  269.     public synchronized void printLog() {
  270.         System.out
  271.                 .println("Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
  272.         System.out.println("Log na izvrsuvanje na akciite:");
  273.         System.out.println("=========================");
  274.         System.out.println("tip\tid\titer\takcija/error");
  275.         System.out.println("=========================");
  276.         for (String l : actions) {
  277.             System.out.println(l);
  278.         }
  279.     }
  280.  
  281.     /**
  282.      * Prints the status of the execution, with the exceptions that has occur
  283.      */
  284.     public void printStatus() {
  285.         finalize();
  286.         if (!TemplateThread.hasException) {
  287.             int poeni = 25;
  288.             if (PointsException.getTotalPoints() == 0) {
  289.                 System.out
  290.                         .println("Procesot e uspesno sinhroniziran. Osvoeni 25 poeni.");
  291.             } else {
  292.                 poeni -= PointsException.getTotalPoints();
  293.                 PointsException.printErrors();
  294.                 System.out.println("Maksimalni osvoeni poeni: " + poeni);
  295.             }
  296.  
  297.         } else {
  298.             System.out
  299.                     .println("Procesot ne e sinhroniziran spored uslovite na zadacata");
  300.             printLog();
  301.             System.out
  302.                     .println("====================================================");
  303.             PointsException.printErrors();
  304.             int total = (25 - PointsException.getTotalPoints());
  305.             if (total < 0) {
  306.                 total = 0;
  307.             }
  308.             System.out.println("Maksimum Poeni: " + total);
  309.         }
  310.  
  311.     }
  312. }
  313.  
  314. class BoundCounterWithRaceConditionCheck {
  315.  
  316.     private static final int RACE_CONDITION_POINTS = 25;
  317.     private static final String RACE_CONDITION_MESSAGE = "Race condition occured";
  318.  
  319.     private int value;
  320.     private Integer maxAllowed;
  321.     private Integer minAllowed;
  322.     private int maxErrorPoints;
  323.     private int minErrorPoints;
  324.     private String maxErrorMessage;
  325.     private String minErrorMessage;
  326.  
  327.     private int max;
  328.  
  329.     /**
  330.      *
  331.      * @param value
  332.      */
  333.     public BoundCounterWithRaceConditionCheck(int value) {
  334.         super();
  335.         this.value = value;
  336.         this.max = value;
  337.     }
  338.  
  339.     /**
  340.      *
  341.      * @param value
  342.      *            initial value
  343.      * @param maxAllowed
  344.      *            upper bound of the value
  345.      * @param maxErrorPoints
  346.      *            how many points are lost with the max value constraint
  347.      *            violation
  348.      * @param maxErrorMessage
  349.      *            message shown when the upper bound constrain is violated
  350.      * @param minAllowed
  351.      *            lower bound of the value
  352.      * @param minErrorPoints
  353.      *            how many points are lost with the min value constraint
  354.      *            violation
  355.      * @param minErrorMessage
  356.      *            message shown when the lower bound constrain is violated
  357.      */
  358.     public BoundCounterWithRaceConditionCheck(int value, Integer maxAllowed, int maxErrorPoints,
  359.                                               String maxErrorMessage, Integer minAllowed, int minErrorPoints,
  360.                                               String minErrorMessage) {
  361.         super();
  362.         this.value = value;
  363.         this.max = value;
  364.         this.maxAllowed = maxAllowed;
  365.         this.minAllowed = minAllowed;
  366.         this.maxErrorPoints = maxErrorPoints;
  367.         this.minErrorPoints = minErrorPoints;
  368.         this.maxErrorMessage = maxErrorMessage;
  369.         this.minErrorMessage = minErrorMessage;
  370.     }
  371.  
  372.     /**
  373.      *
  374.      * @return the maximum value of the integer variable that occurred at some
  375.      *         point of the execution
  376.      */
  377.     public int getMax() {
  378.         return max;
  379.     }
  380.  
  381.     /**
  382.      *
  383.      * @return the current value
  384.      */
  385.     public int getValue() {
  386.         return value;
  387.     }
  388.  
  389.     public void setValue(int value) {
  390.         this.value = value;
  391.     }
  392.  
  393.     /**
  394.      * Testing for race condition. NOTE: there are no guarantees that the race
  395.      * condition will be detected
  396.      *
  397.      * @return
  398.      */
  399.     public PointsException checkRaceCondition() {
  400.         return checkRaceCondition(3, RACE_CONDITION_MESSAGE);
  401.     }
  402.  
  403.     /**
  404.      * Testing for race condition. NOTE: there are no guarantees that the race
  405.      * condition will be detected, but higher the time argument is, the
  406.      * probability for race condition occurrence is higher
  407.      *
  408.      * @return
  409.      */
  410.     public PointsException checkRaceCondition(int time, String message) {
  411.         int val;
  412.  
  413.         synchronized (this) {
  414.             val = value;
  415.         }
  416.         Switcher.forceSwitch(time);
  417.         if (val != value) {
  418.             PointsException e = new PointsException(RACE_CONDITION_POINTS,
  419.                     message);
  420.             return e;
  421.         }
  422.         return null;
  423.  
  424.     }
  425.  
  426.     public PointsException incrementWithMax() {
  427.         return incrementWithMax(true);
  428.     }
  429.  
  430.     public PointsException incrementWithMax(boolean checkRaceCondition) {
  431.         if (checkRaceCondition) {
  432.             PointsException raceCondition = checkRaceCondition();
  433.             if (raceCondition != null) {
  434.                 return raceCondition;
  435.             }
  436.         }
  437.         synchronized (this) {
  438.             value++;
  439.  
  440.             if (value > max) {
  441.                 max = value;
  442.             }
  443.             if (maxAllowed != null) {
  444.                 if (value > maxAllowed) {
  445.                     PointsException e = new PointsException(maxErrorPoints,
  446.                             maxErrorMessage);
  447.                     return e;
  448.                 }
  449.             }
  450.         }
  451.  
  452.         return null;
  453.     }
  454.  
  455.     public PointsException decrementWithMin() {
  456.         return decrementWithMin(true);
  457.     }
  458.  
  459.     public PointsException decrementWithMin(boolean checkRaceCondition) {
  460.         if (checkRaceCondition) {
  461.             PointsException raceCondition = checkRaceCondition();
  462.             if (raceCondition != null) {
  463.                 return raceCondition;
  464.             }
  465.         }
  466.  
  467.         synchronized (this) {
  468.             value--;
  469.             if (minAllowed != null) {
  470.                 if (value < minAllowed) {
  471.                     PointsException e = new PointsException(minErrorPoints,
  472.                             minErrorMessage);
  473.                     return e;
  474.                 }
  475.             }
  476.         }
  477.         return null;
  478.     }
  479. }
  480.  
  481. class PointsException extends RuntimeException {
  482.  
  483.     private static HashMap<String, PointsException> exceptions = new HashMap<String, PointsException>();
  484.     private int points;
  485.  
  486.     public PointsException(int points, String message) {
  487.         super(message);
  488.         this.points = points;
  489.         exceptions.put(message, this);
  490.     }
  491.  
  492.     public static int getTotalPoints() {
  493.         int sum = 0;
  494.         for (PointsException e : exceptions.values()) {
  495.             sum += e.getPoints();
  496.         }
  497.         return sum;
  498.     }
  499.  
  500.     public static void printErrors() {
  501.         System.out.println("Gi imate slednite greski: ");
  502.         for (Map.Entry<String, PointsException> e : exceptions.entrySet()) {
  503.             System.out.println(String.format("[%s] : (-%d)", e.getKey(), e
  504.                     .getValue().getPoints()));
  505.         }
  506.     }
  507.  
  508.     public int getPoints() {
  509.         return points;
  510.     }
  511. }
  512. abstract class ProblemExecution {
  513.  
  514.     public static void start(HashSet<Thread> threads, AbstractState state)
  515.             throws Exception {
  516.  
  517.  
  518.         // start the threads
  519.         for (Thread t : threads) {
  520.             t.start();
  521.         }
  522.  
  523.         // wait threads to finish
  524.         for (Thread t : threads) {
  525.             t.join(1000);
  526.         }
  527.  
  528.         // check for deadlock
  529.         for (Thread t : threads) {
  530.             if (t.isAlive()) {
  531.                 t.interrupt();
  532.                 if (t instanceof TemplateThread) {
  533.                     TemplateThread tt = (TemplateThread) t;
  534.                     tt.setException(new PointsException(25, "DEADLOCK"));
  535.                 }
  536.             }
  537.         }
  538.  
  539.         // print the status
  540.         state.printStatus();
  541.     }
  542.  
  543. }
  544. class Switcher {
  545.     private static final Random RANDOM = new Random();
  546.  
  547.     /*
  548.      * This method pauses the current thread i.e. changes its state to be
  549.      * Blocked. This should force thread switch if there are threads waiting
  550.      */
  551.     public static void forceSwitch(int range) {
  552.         try {
  553.             Thread.sleep(RANDOM.nextInt(range));
  554.         } catch (InterruptedException e) {
  555.         }
  556.     }
  557. }
  558. abstract class TemplateThread extends Thread {
  559.  
  560.     static boolean hasException = false;
  561.     int numRuns = 1;
  562.     public int iteration = 0;
  563.     protected Exception exception = null;
  564.  
  565.     public TemplateThread(int numRuns) {
  566.         this.numRuns = numRuns;
  567.     }
  568.  
  569.     public abstract void execute() throws InterruptedException;
  570.  
  571.     @Override
  572.     public void run() {
  573.         try {
  574.             for (int i = 0; i < numRuns&&!hasException; i++) {
  575.                 execute();
  576.                 iteration++;
  577.  
  578.             }
  579.         } catch (InterruptedException e) {
  580.             // Do nothing
  581.         } catch (Exception e) {
  582.             exception = e;
  583.             e.printStackTrace();
  584.             hasException = true;
  585.         }
  586.     }
  587.  
  588.     public void setException(Exception exception) {
  589.         this.exception = exception;
  590.         hasException = true;
  591.     }
  592.  
  593.     @Override
  594.     public String toString() {
  595.         Thread current = Thread.currentThread();
  596.         if (numRuns > 1) {
  597.             return String.format("%s\t%d\t%d", ""
  598.                             + current.getClass().getSimpleName().charAt(0), getId(),
  599.                     iteration);
  600.         } else {
  601.             return String.format("%s\t%d\t", ""
  602.                     + current.getClass().getSimpleName().charAt(0), getId());
  603.         }
  604.     }
  605. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement