Advertisement
Guest User

Untitled

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