Advertisement
Guest User

Untitled

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