Advertisement
Guest User

Untitled

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