Advertisement
Guest User

Untitled

a guest
Mar 21st, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.51 KB | None | 0 0
  1. VTORA:
  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.  
  12. /**
  13. *
  14. * @author ristes
  15. */
  16. public class TemplateNumRunsAndNumInstances {
  17.  
  18. //TODO: definirajte gi semaforite i ostanatite promenlivi ovde (mora site da se static)
  19. static Semaphore wakeUP;
  20. static Semaphore lock;
  21. static Semaphore enter;
  22. static Semaphore go;
  23.  
  24. static boolean sleep;
  25. static int clients;
  26.  
  27. /**
  28. * Metod koj treba da gi inicijalizira vrednostite na semaforite i
  29. * ostanatite promenlivi za sinhronizacija.
  30. *
  31. *
  32. * TODO: da se implementira
  33. *
  34. */
  35. public static void init(int numBarbers) {
  36. wakeUP = new Semaphore(0);
  37. lock = new Semaphore(1);
  38. go = new Semaphore(0);
  39. enter = new Semaphore(0);
  40. clients = 0;
  41. sleep = true;
  42. }
  43.  
  44. static class Barber extends TemplateThread {
  45.  
  46. public int barberId;
  47.  
  48. public Barber(int numRuns, int barberId) {
  49. super(numRuns);
  50. this.barberId = barberId;
  51. }
  52.  
  53. /**
  54. * Da se implementira odnesuvanjeto na berberot spored baranjeto na
  55. * zadacata.
  56. *
  57. *
  58. * TODO: da se implementira
  59. *
  60. */
  61. public void execute() throws InterruptedException {
  62.  
  63. // koga 5tiot klient ke notificira, berberot treba da se razbudi
  64. if (sleep) {
  65. wakeUP.acquire();
  66. sleep = false;
  67. state.barberWakeUp();
  68. }
  69. // koga klientot ke pristigne, go vika klientot da vleze
  70.  
  71. state.barberCallCustomer();
  72. go.release();
  73.  
  74. enter.acquire();
  75.  
  76. lock.acquire();
  77. --clients;
  78. lock.release();
  79.  
  80. // koga klientot ke vleze, go potstrizuva
  81. state.cutHair();
  82.  
  83. // proveruva dali ima klienti koi cekaat, ako nema, zaspiva
  84.  
  85. lock.acquire();
  86. if (clients == 0) {
  87. state.barberGoToSleep();
  88. sleep = true;
  89. }
  90. lock.release();
  91.  
  92. }
  93. }
  94.  
  95. static class Consumer extends TemplateThread {
  96.  
  97. public Consumer(int numRuns) {
  98. super(numRuns);
  99. }
  100.  
  101. /**
  102. * Da se implementira odnesuvanjeto na ucesnikot spored uslovite na
  103. * zadacata.
  104. */
  105. public void execute() throws InterruptedException {
  106. lock.acquire();
  107. state.customerArrived();
  108. clients++;
  109. if (clients == 5 && sleep) wakeUP.release();
  110. lock.release();
  111.  
  112.  
  113. // dokolku e pettiot, go budi berberot
  114. // koga ke bide povikan, vleguva
  115. go.acquire();
  116. state.customerEntry();
  117. enter.release();
  118.  
  119. // klientot vlegol vo berbernicata i e spremen za potstrizuvanje
  120. // koga ke go potstrizat, plakja
  121. state.customerPay();
  122.  
  123.  
  124. }
  125. }
  126. //<editor-fold defaultstate="collapsed" desc="This is the template code" >
  127. static State state;
  128.  
  129. static class State {
  130.  
  131. private static final Random RANDOM = new Random();
  132. private static final int RANDOM_RANGE = 5;
  133. @SuppressWarnings("unused")
  134. private final int numBarbers;
  135. private boolean barberWaked[];
  136.  
  137. public State(int numBarbers) {
  138. this.numBarbers = numBarbers;
  139. barberWaked = new boolean[numBarbers];
  140. }
  141. private int arrivedCustomers = 0;
  142. private int calledCustomers = 0;
  143. @SuppressWarnings("unused")
  144. private int maxCuttings = 0;
  145. private int numCuttings = 0;
  146.  
  147. public synchronized void customerArrived() throws RuntimeException {
  148. log(null, "customer arrived");
  149. arrivedCustomers++;
  150. }
  151.  
  152. public synchronized void barberWakeUp() throws RuntimeException {
  153. Barber b = (Barber) Thread.currentThread();
  154. if (barberWaked[b.barberId]) {
  155. PointsException e = new PointsException(5, "Berberot e veke buden i nema potreba da se razbudi.");
  156. log(e, null);
  157. } else {
  158. log(null, "the barber is waked up");
  159. barberWaked[b.barberId] = true;
  160. }
  161. }
  162.  
  163. public synchronized void barberCallCustomer() throws RuntimeException {
  164. log(null, "the barber calls the customer");
  165. if (arrivedCustomers <= 0) {
  166. PointsException e = new PointsException(5, "Brojot na klienti koi cekaat e 0 i nema koj da bide povikan.");
  167. log(e, null);
  168. }
  169. calledCustomers++;
  170. }
  171.  
  172. public synchronized void customerEntry() throws RuntimeException {
  173. log(null, "customer sits in the chair");
  174. if (arrivedCustomers <= 0) {
  175. PointsException e = new PointsException(5, "Brojot na klienti koi cekaat e 0 i nema koj da vleze.");
  176. log(e, null);
  177. }
  178. if (calledCustomers <= 0) {
  179. PointsException e = new PointsException(5, "Nema povikano klient i ne moze da vleze.");
  180. log(e, null);
  181. }
  182. arrivedCustomers--;
  183. calledCustomers--;
  184.  
  185. numCuttings++;
  186. }
  187.  
  188. public void cutHair() throws RuntimeException {
  189. synchronized (this) {
  190. if (numCuttings <= 0) {
  191. PointsException e = new PointsException(5, "Nema prisuten klient za potstrizuvanje");
  192. log(e, null);
  193. }
  194.  
  195. log(null, "berber cuts the customer hair");
  196. }
  197. try {
  198. int r;
  199. synchronized (this) {
  200. r = RANDOM.nextInt(RANDOM_RANGE);
  201. }
  202. Thread.sleep(r);
  203. } catch (Exception e) {
  204. //do nothing
  205. }
  206. synchronized (this) {
  207. if (numCuttings <= 0) {
  208. PointsException e = new PointsException(5, "Brojot na klienti koi se strizat e 0 i nema koj da izleze.");
  209. log(e, null);
  210. }
  211. numCuttings--;
  212. }
  213.  
  214. }
  215.  
  216. public synchronized void customerPay() throws RuntimeException {
  217. log(null, "customer is paying and leaving the shop");
  218.  
  219.  
  220. }
  221.  
  222. public synchronized void barberGoToSleep() throws RuntimeException {
  223. Barber b = (Barber) Thread.currentThread();
  224. if (!barberWaked[b.barberId]) {
  225. PointsException e = new PointsException(5, "Berberite veke spijat i ne moze da se prezaspijat.");
  226. log(e, null);
  227. }
  228. if (arrivedCustomers > 0) {
  229. PointsException e = new PointsException(5, "Seuste ima klienti koi cekaat i berberot ne moze da odi na spienje.");
  230. log(e, null);
  231. }
  232. log(null, "all barbers go to sleap");
  233. barberWaked[b.barberId] = false;
  234. }
  235. private List<String> actions = new ArrayList<String>();
  236. @SuppressWarnings("unused")
  237. private List<PointsException> exceptions = new ArrayList<PointsException>();
  238.  
  239. private synchronized void log(PointsException e, String action) {
  240. TemplateThread t = (TemplateThread) Thread.currentThread();
  241. if (e == null) {
  242. actions.add(t.toString() + "\t(a): " + action);
  243. } else {
  244. t.setException(e);
  245. actions.add(t.toString() + "\t(e): " + e.getMessage());
  246. }
  247. }
  248.  
  249. public synchronized void printLog() {
  250. System.out.println("Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
  251. System.out.println("Log na izvrsuvanje na akciite:");
  252. System.out.println("=========================");
  253. System.out.println("tip\tid\titer\takcija/error");
  254. System.out.println("=========================");
  255. for (String l : actions) {
  256. System.out.println(l);
  257. }
  258. }
  259.  
  260. public void printStatus() {
  261. if (!TemplateThread.hasException) {
  262. int poeni = 25;
  263. if (PointsException.getTotalPoints() == 0) {
  264. System.out.println("Procesot e uspesno sinhroniziran. Osvoeni 25 poeni.");
  265. } else {
  266. poeni -= PointsException.getTotalPoints();
  267. PointsException.printErrors();
  268. System.out.println("Osvoeni poeni: " + poeni);
  269. }
  270.  
  271. } else {
  272. System.out.println("Procesot ne e sinhroniziran spored uslovite na zadacata");
  273. printLog();
  274. System.out.println("====================================================");
  275. PointsException.printErrors();
  276. System.out.println("Maksimum Poeni: " + (25 - PointsException.getTotalPoints()));
  277. }
  278.  
  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. @SuppressWarnings("unused")
  288. private Exception exception = null;
  289.  
  290. public TemplateThread(int numRuns) {
  291. this.numRuns = numRuns;
  292. }
  293.  
  294. abstract void execute() throws InterruptedException;
  295.  
  296. @Override
  297. public void run() {
  298. try {
  299. for (int i = 0; i < numRuns && !hasException; i++) {
  300. execute();
  301. iteration++;
  302.  
  303. }
  304. } catch (InterruptedException e) {
  305. // Do nothing
  306. } catch (Exception e) {
  307. exception = e;
  308. hasException = true;
  309. }
  310. }
  311.  
  312. public void setException(Exception exception) {
  313. this.exception = exception;
  314. hasException = true;
  315. }
  316.  
  317. @Override
  318. public String toString() {
  319. Thread current = Thread.currentThread();
  320. if (numRuns > 1) {
  321. return String.format("%s\t%d\t%d", "" + current.getClass().getSimpleName().charAt(0), getId(), iteration);
  322. } else {
  323. return String.format("%s\t%d\t", "" + current.getClass().getSimpleName().charAt(0), getId());
  324. }
  325. }
  326. }
  327.  
  328. @SuppressWarnings("serial")
  329. static class PointsException extends RuntimeException {
  330.  
  331. private static HashMap<String, PointsException> exceptions = new HashMap<String, PointsException>();
  332. private int points;
  333.  
  334. public PointsException(int points, String message) {
  335. super(message);
  336. this.points = points;
  337. exceptions.put(message, this);
  338. }
  339.  
  340. public static int getTotalPoints() {
  341. int sum = 0;
  342. for (PointsException e : exceptions.values()) {
  343. sum += e.getPoints();
  344. }
  345. return sum;
  346. }
  347.  
  348. public static void printErrors() {
  349. System.out.println("Gi imate slednite greski: ");
  350. for (Map.Entry<String, PointsException> e : exceptions.entrySet()) {
  351. System.out.println(String.format("[%s] : (-%d)", e.getKey(), e.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 brBarbers = s.nextInt();
  371. int brKonzumeri = s.nextInt();
  372. int numBarberRuns = s.nextInt();
  373. int numCustomerRuns = s.nextInt();
  374. init(brBarbers);
  375.  
  376. state = new State(brBarbers);
  377. HashSet<Thread> threads = new HashSet<Thread>();
  378.  
  379. for (int i = 0; i < brBarbers; i++) {
  380. Barber prod = new Barber(numBarberRuns, i);
  381. threads.add(prod);
  382. prod.start();
  383. Consumer c = new Consumer(numCustomerRuns);
  384. threads.add(c);
  385. c.start();
  386. }
  387.  
  388. for (int i = 0; i < brKonzumeri / 2 - brBarbers; i++) {
  389. Consumer c = new Consumer(numCustomerRuns);
  390. threads.add(c);
  391. c.start();
  392. }
  393. try {
  394. Thread.sleep(50);
  395. } catch (Exception e) {
  396. //do nothing
  397. }
  398. for (int i = 0; i < brKonzumeri / 2; i++) {
  399. Consumer c = new Consumer(numCustomerRuns);
  400. threads.add(c);
  401. c.start();
  402. }
  403.  
  404.  
  405. for (Thread t : threads) {
  406. t.join(1000);
  407. }
  408.  
  409. for (Thread t : threads) {
  410. if (t.isAlive()) {
  411. t.interrupt();
  412. }
  413. }
  414.  
  415. state.printStatus();
  416. s.close();
  417. }
  418. //</editor-fold>
  419. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement