Advertisement
Guest User

Untitled

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