Advertisement
nikolaliltek

Музички бенд ОС

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