Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 37.71 KB | None | 0 0
  1. // JAVA IO PRVA GRUPA
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FilenameFilter;
  7. import java.io.IOException;
  8. import java.io.RandomAccessFile;
  9. import java.util.ArrayList;
  10.  
  11. public class ExamIO {
  12.  
  13. public static void main(String[] args) throws IOException {
  14.  
  15. moveWritableTxtFiles(args[0], args[1]);
  16. invertLargeFile(args[2], args[5]);
  17.  
  18. }
  19.  
  20. private static void moveWritableTxtFiles(String from, String to) {
  21. File fromFolder = new File(from);
  22. File toFolder = new File(to);
  23.  
  24. if (!fromFolder.exists()) {
  25. System.out.println("Ne postoi");
  26. }
  27. if (!toFolder.exists()) {
  28. toFolder.mkdirs();
  29. }
  30.  
  31. FilenameFilter filter = new FilenameFilter() {
  32.  
  33. @Override
  34. public boolean accept(File arg0, String arg1) {
  35. return arg1.toLowerCase().endsWith(".txt");
  36. }
  37.  
  38. };
  39. File[] files = fromFolder.listFiles(filter);
  40. for (File f : files) {
  41. if (f.canWrite()) {
  42. f.renameTo(toFolder);
  43. }
  44. }
  45.  
  46. }
  47.  
  48. @SuppressWarnings({ "unused", "resource" })
  49. private static void deserializeData(String source, ArrayList<byte[]> data, long elementLength) throws IOException {
  50. // RandomAccessFile read = new RandomAccessFile(source,"r");
  51. // byte[] niza = new byte[(int)elementLength];
  52. // read.seek(0);
  53. // while((read.read(niza,0,(int) elementLength))!=-1)
  54. // {
  55. // data.add(niza);
  56. // niza = new byte[(int)elementLength];
  57. // }
  58.  
  59. FileInputStream in = new FileInputStream(source);
  60. byte[] buffer = new byte[(int) elementLength];
  61. while (in.read(buffer) != -1) {
  62. data.add(buffer);
  63. buffer = new byte[(int) elementLength];
  64. }
  65. }
  66.  
  67. private static void invertLargeFile(String source, String destination) throws IOException {
  68. File izvor = new File(source);
  69. File destinacija = new File(destination);
  70. RandomAccessFile read = null;
  71. RandomAccessFile write = null;
  72.  
  73. try {
  74. read = new RandomAccessFile(izvor, "r");
  75. write = new RandomAccessFile(destinacija, "rw");
  76.  
  77. for (int i = (int) (read.length() - 1); i >= 0; i--) {
  78. read.seek(i);
  79. write.writeByte(read.readByte());
  80. }
  81.  
  82. } catch (FileNotFoundException e) {
  83. // TODO Auto-generated catch block
  84. e.printStackTrace();
  85. } finally {
  86. if (read != null) {
  87. read.close();
  88. }
  89. if (write != null) {
  90. write.close();
  91. }
  92. }
  93. }
  94.  
  95. }
  96. _______________________________________________________________________________
  97.  
  98. // JAVA IO VTORA GRUPA
  99.  
  100.  
  101. import java.io.BufferedReader;
  102. import java.io.BufferedWriter;
  103. import java.io.File;
  104. import java.io.FileOutputStream;
  105. import java.io.FileReader;
  106. import java.io.FileWriter;
  107. import java.io.FilenameFilter;
  108. import java.io.IOException;
  109. import java.io.OutputStream;
  110. import java.io.RandomAccessFile;
  111. import java.util.ArrayList;
  112.  
  113. class ExamIO2 {
  114. public static void main(String[] args) throws IOException {
  115.  
  116. long size = Long.parseLong(args[2]);
  117. copyLargeTxtFiles(args[0], args[1], size);
  118.  
  119. long position = 6;// Long.parseLong(args[3]);
  120. long elementLength = 6;// Long.parseLong(args[4]);
  121.  
  122. String destination = "C:\\Users\\Tech\\Desktop\\destinacija.txt";
  123. ArrayList<byte[]> data = new ArrayList<byte[]>();
  124.  
  125. serializeData(destination, data);
  126.  
  127. deserializeDataAtPosition("C:\\Users\\Tech\\Desktop\\izvor.jpg", position, elementLength);
  128.  
  129. }
  130.  
  131. @SuppressWarnings({ "resource" })
  132. private static void serializeData(String destination, ArrayList<byte[]> data) throws IOException {
  133.  
  134.  
  135. OutputStream out = new FileOutputStream(destination);
  136. for(byte[] b : data)
  137. {
  138. out.write(b);
  139. }
  140.  
  141. }
  142.  
  143. @SuppressWarnings("resource")
  144. private static byte[] deserializeDataAtPosition(String source, long position, long elementLength)
  145. throws IOException {
  146.  
  147. byte[] niza = new byte[(int) elementLength];
  148. RandomAccessFile read = new RandomAccessFile(source, "r");
  149. read.seek(((position - 1) * elementLength));
  150. read.read(niza, 0, (int) elementLength);
  151. for (byte b : niza) {
  152. System.out.print(b);
  153. }
  154. return niza;
  155.  
  156. }
  157.  
  158. private static void copyLargeTxtFiles(String from, String to, long size) throws IOException {
  159. File fromFolder = new File(from);
  160. File toFolder = new File(to);
  161.  
  162. if (!fromFolder.exists()) {
  163. System.out.println("Ne postoi");
  164. }
  165. if (!toFolder.exists()) {
  166. toFolder.mkdirs();
  167. }
  168.  
  169. FilenameFilter filter = new FilenameFilter() {
  170.  
  171. public boolean accept(File dir, String name) {
  172. return name.toLowerCase().endsWith(".txt");
  173. }
  174.  
  175. };
  176.  
  177. File[] files = fromFolder.listFiles(filter);
  178. for (File f : files) {
  179. if (f.length() > size) {
  180. File copy = copyText(f);
  181. copy.renameTo(toFolder);
  182. }
  183. }
  184.  
  185. }
  186.  
  187. @SuppressWarnings("resource")
  188. private static File copyText(File fromFolder) throws IOException {
  189. File copy = new File(fromFolder.getParentFile() + "\\copyOf" + fromFolder.getName());
  190. BufferedReader br = new BufferedReader(new FileReader(fromFolder));
  191. BufferedWriter bw = new BufferedWriter(new FileWriter(copy));
  192.  
  193. String line = null;
  194. while ((line = br.readLine()) != null) {
  195. bw.write(line);
  196. bw.flush();
  197. }
  198. bw.close();
  199. return copy;
  200.  
  201. }
  202. }
  203.  
  204. ___________________________________________________________________________________
  205.  
  206. // JAVA IO JUNSKA SESIJA
  207.  
  208. package junskaSesija;
  209.  
  210. import java.io.File;
  211. import java.io.FileNotFoundException;
  212. import java.io.FilenameFilter;
  213. import java.io.IOException;
  214. import java.io.RandomAccessFile;
  215.  
  216. public class JunskaIO {
  217.  
  218. public static void main(String[] args) throws IOException {
  219.  
  220. String in = args[0];
  221. String out = args[1];
  222.  
  223. manage(in, out);
  224.  
  225. }
  226.  
  227. private static void manage(String in, String out) throws IOException {
  228. // TODO Auto-generated method stub
  229.  
  230. FilenameFilter filter = new FilenameFilter() {
  231.  
  232. @Override
  233. public boolean accept(File dir, String name) {
  234. // TODO Auto-generated method stub
  235. return name.toLowerCase().endsWith(".dat");
  236. }
  237.  
  238. };
  239.  
  240. File source = new File(in);
  241. File destination = new File(out);
  242. File resources = new File("C:\\Users\\Tech\\Desktop\\resource\\writable-content.txt");
  243.  
  244. if (!source.exists()) {
  245. System.out.println("Ne postoi");
  246. }
  247.  
  248. if (destination.exists()) {
  249. File[] files = destination.listFiles();
  250. for (File f : files) {
  251. f.delete();
  252. }
  253. }
  254.  
  255. if (!destination.exists()) {
  256. destination.mkdirs();
  257. }
  258.  
  259. File[] file = source.listFiles(filter);
  260. for (File f : file) {
  261. if (f.canWrite()) {
  262. f.renameTo(destination);
  263. System.out.println("Pomestuvam " + f.getAbsolutePath());
  264. }
  265.  
  266. if (!f.canWrite()) {
  267. RandomAccessFile read = new RandomAccessFile(f, "r");
  268. RandomAccessFile write = new RandomAccessFile(resources, "rw");
  269.  
  270. for (int i = 0; i < read.length(); i++) {
  271. read.seek(i);
  272. write.writeByte(read.readByte());
  273. System.out.println("Dopisuvam " + f.getAbsolutePath());
  274. }
  275.  
  276. // String line = null;
  277. // while((line = read.readLine())!=null)
  278. // {
  279. // write.writeBytes(line);
  280. // }
  281. }
  282.  
  283. if (f.isHidden()) {
  284. f.delete();
  285. System.out.println("Zbunet sum");
  286. }
  287. }
  288.  
  289. }
  290.  
  291. }
  292.  
  293.  
  294. ____________________________________________________________________________
  295.  
  296. // TANC SO STUDENTITE
  297.  
  298. import java.util.ArrayList;
  299. import java.util.HashSet;
  300. import java.util.List;
  301. import java.util.Random;
  302. import java.util.concurrent.Semaphore;
  303.  
  304. public class TancSoStudentite {
  305. // TODO: Definicija na globalni promenlivi i semafori
  306. public static Semaphore maski;
  307. public static Semaphore zenski;
  308. public static Semaphore spremna;
  309. public static Semaphore parovi;
  310.  
  311. public void init() {
  312. // TODO: da se implementira
  313. maski = new Semaphore(10);
  314. zenski = new Semaphore(10);
  315. spremna = new Semaphore(0);
  316. parovi = new Semaphore(3);
  317.  
  318. }
  319.  
  320. class Masko extends Thread {
  321. // TODO: Definicija na promenlivi za sostojbata
  322.  
  323. public void ucestvo() throws InterruptedException {
  324. // TODO: da se implementira
  325.  
  326. maski.acquire();
  327. show.presobleci();
  328. maski.release();
  329. spremna.acquire();
  330. parovi.acquire();
  331. show.tancuvaj();
  332. parovi.release();
  333. }
  334.  
  335. @Override
  336. public void run() {
  337. try {
  338. ucestvo();
  339. } catch (InterruptedException e) {
  340. // Do nothing
  341. } catch (Exception e) {
  342. exception = e;
  343. hasException = true;
  344. }
  345. }
  346.  
  347. @Override
  348. public String toString() {
  349. return String.format("m\t%d", getId());
  350. }
  351.  
  352. public Exception exception = null;
  353. }
  354.  
  355. class Zensko extends Thread {
  356. // TODO: Definicija na promenlivi za sostojbata
  357.  
  358. public void ucestvo() throws InterruptedException {
  359. // TODO: da se implementira
  360. zenski.acquire();
  361. show.presobleci();
  362. zenski.release();
  363. spremna.release();
  364.  
  365. }
  366.  
  367. @Override
  368. public void run() {
  369. try {
  370. ucestvo();
  371. } catch (InterruptedException e) {
  372. // Do nothing
  373. } catch (Exception e) {
  374. exception = e;
  375. hasException = true;
  376. }
  377. }
  378.  
  379. @Override
  380. public String toString() {
  381. return String.format("z\t%d", getId());
  382. }
  383.  
  384. public Exception exception = null;
  385. }
  386.  
  387. public static void main(String[] args) {
  388. try {
  389. TancSoStudentite environment = new TancSoStudentite();
  390. environment.start();
  391. } catch (Exception ex) {
  392. ex.printStackTrace();
  393. }
  394. }
  395.  
  396. public void start() throws Exception {
  397. show = new Show();
  398. init();
  399. HashSet<Thread> threads = new HashSet<Thread>();
  400. for (int i = 0; i < BROJ_INSTANCI; i++) {
  401. Zensko z = new Zensko();
  402. Masko m = new Masko();
  403. threads.add(z);
  404. threads.add(m);
  405. }
  406.  
  407. for (Thread t : threads) {
  408. t.start();
  409. }
  410.  
  411. boolean valid = true;
  412. for (Thread t : threads) {
  413. if (!hasException) {
  414. t.join();
  415. } else {
  416. t.interrupt();
  417. }
  418. }
  419. show.printStatus();
  420.  
  421. }
  422.  
  423. public class Show {
  424.  
  425. public static final int BROJ_GARDEROBA = 10;
  426. public static final int BROJ_TEREN = 3;
  427. public static final int TYPE_MASKO = 1;
  428. public static final int TYPE_ZENSKO = 2;
  429. public static final int TYPE_UNKNOWN = -1;
  430.  
  431. public Show() {
  432. }
  433.  
  434. public int brojMaskiGarderoba = 0;
  435. public int brojZenskiGarderoba = 0;
  436. public int brojTancuvanja = 0;
  437. public int maxMaskiGarderoba = 0;
  438. public int maxZenskiGarderoba = 0;
  439. public int maxTancuvanja = 0;
  440.  
  441. public void presobleci() throws RuntimeException {
  442. log(null, "presobleci start");
  443. Thread t = Thread.currentThread();
  444. if (t instanceof Masko) {
  445. synchronized (RANDOM) {
  446. brojMaskiGarderoba++;
  447. if (brojMaskiGarderoba > 10) {
  448. exception("Ne moze da ima poveke od 10 maski vo maskata garderoba.");
  449. }
  450. if (brojMaskiGarderoba > maxMaskiGarderoba) {
  451. maxMaskiGarderoba = brojMaskiGarderoba;
  452. }
  453. }
  454. waitRandom();
  455. synchronized (RANDOM) {
  456. brojMaskiGarderoba--;
  457. }
  458. } else {
  459. synchronized (RANDOM) {
  460. brojZenskiGarderoba++;
  461. if (brojZenskiGarderoba > 10) {
  462. exception("Ne moze da ima poveke od 10 zenski vo zenskata garderoba.");
  463. }
  464. if (brojZenskiGarderoba > maxZenskiGarderoba) {
  465. maxZenskiGarderoba = brojZenskiGarderoba;
  466. }
  467. }
  468. waitRandom();
  469. synchronized (RANDOM) {
  470. brojZenskiGarderoba--;
  471. }
  472. }
  473. log(null, "presobleci kraj");
  474. }
  475.  
  476. public void tancuvaj() throws RuntimeException {
  477. log(null, "tancuvaj start");
  478. synchronized (RANDOM) {
  479. brojTancuvanja++;
  480. if (brojTancuvanja > BROJ_TEREN) {
  481. exception("Ne moze paralelno da tancuvaat poveke od 3 para.");
  482. }
  483.  
  484. if (brojTancuvanja > maxTancuvanja) {
  485. maxTancuvanja = brojTancuvanja;
  486. }
  487. }
  488. waitRandom();
  489. synchronized (RANDOM) {
  490. brojTancuvanja--;
  491. }
  492. log(null, "tancuvaj kraj");
  493. }
  494.  
  495. private void waitRandom() {
  496. try {
  497. int r;
  498. synchronized (RANDOM) {
  499. r = RANDOM.nextInt(RANDOM_RANGE);
  500. }
  501. Thread.sleep(r);
  502. } catch (Exception e) {
  503. // do nothing
  504. }
  505. }
  506.  
  507. private void exception(String message) {
  508. RuntimeException e = new RuntimeException(message);
  509. log(e, null);
  510. hasError = true;
  511. throw e;
  512. }
  513.  
  514. public int getType() {
  515. Thread t = Thread.currentThread();
  516. if (t instanceof Masko) {
  517. return TYPE_MASKO;
  518. } else if (t instanceof Zensko) {
  519. return TYPE_ZENSKO;
  520. } else {
  521. return TYPE_UNKNOWN;
  522. }
  523. }
  524.  
  525. private synchronized void log(RuntimeException e, String action) {
  526. Thread t = Thread.currentThread();
  527. if (e == null) {
  528. actions.add(t.toString() + "\t(a): " + action);
  529. } else {
  530. actions.add(t.toString() + "\t(e): " + e.getMessage());
  531. }
  532. }
  533.  
  534. public synchronized void printLog() {
  535. System.out.println(
  536. "Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
  537. System.out.println("Log na izvrsuvanje na akciite:");
  538. System.out.println("=========================");
  539. System.out.println("(tip m<=>Masko, tip z<=>Zensko)");
  540. System.out.println("tip\tid\takcija/error");
  541. System.out.println("=========================");
  542. for (String l : actions) {
  543. System.out.println(l);
  544. }
  545. }
  546.  
  547. public void printStatus() {
  548. if (!hasError) {
  549. int poeni = 25;
  550. System.out.println("Procesot e uspesno sinhroniziran");
  551. if (show.maxMaskiGarderoba == 1 || show.maxZenskiGarderoba == 1) {
  552. System.out.println("\t-no ima maksimum eden ucesnik vo garderobata.");
  553. poeni -= 5;
  554. }
  555. if (show.maxTancuvanja == 1) {
  556. System.out.println("\t-no ima maksimum edna proverka vo eden moment.");
  557. poeni -= 5;
  558. }
  559.  
  560. System.out.println("Osvoeni poeni: " + poeni);
  561.  
  562. } else {
  563. System.out.println("Procesot ne e sinhroniziran spored uslovite na zadacata");
  564. show.printLog();
  565. System.out.println("Maksimum mozni poeni: 15");
  566. }
  567.  
  568. }
  569.  
  570. private List<String> actions = new ArrayList<String>();
  571. private boolean hasError = false;
  572. }
  573.  
  574. // Konstanti
  575. public static int BROJ_INSTANCI = 1000;
  576. public static final Random RANDOM = new Random();
  577. public static final int RANDOM_RANGE = 3;
  578. // Instanca od bafferot
  579. public Show show;
  580. public boolean hasException = false;
  581. }
  582.  
  583. ___________________________________________________________________________________
  584.  
  585. // ZASPAN BERBER
  586.  
  587. import java.util.ArrayList;
  588. import java.util.HashMap;
  589. import java.util.HashSet;
  590. import java.util.List;
  591. import java.util.Map;
  592. import java.util.Random;
  593. import java.util.Scanner;
  594. import java.util.concurrent.Semaphore;
  595.  
  596. /**
  597. *
  598. * @author ristes
  599. */
  600. public class TemplateNumRunsAndNumInstances {
  601.  
  602. //TODO: definirajte gi semaforite i ostanatite promenlivi ovde (mora site da se static)
  603. static Semaphore wakeUP;
  604. static Semaphore lock;
  605. static Semaphore enter;
  606. static Semaphore go;
  607.  
  608. static boolean sleep;
  609. static int clients;
  610.  
  611. /**
  612. * Metod koj treba da gi inicijalizira vrednostite na semaforite i
  613. * ostanatite promenlivi za sinhronizacija.
  614. *
  615. *
  616. * TODO: da se implementira
  617. *
  618. */
  619. public static void init(int numBarbers) {
  620. wakeUP = new Semaphore(0);
  621. lock = new Semaphore(1);
  622. go = new Semaphore(0);
  623. enter = new Semaphore(0);
  624. clients = 0;
  625. sleep = true;
  626. }
  627.  
  628. static class Barber extends TemplateThread {
  629.  
  630. public int barberId;
  631.  
  632. public Barber(int numRuns, int barberId) {
  633. super(numRuns);
  634. this.barberId = barberId;
  635. }
  636.  
  637. /**
  638. * Da se implementira odnesuvanjeto na berberot spored baranjeto na
  639. * zadacata.
  640. *
  641. *
  642. * TODO: da se implementira
  643. *
  644. */
  645. public void execute() throws InterruptedException {
  646.  
  647. // koga 5tiot klient ke notificira, berberot treba da se razbudi
  648. if (sleep) {
  649. wakeUP.acquire();
  650. sleep = false;
  651. state.barberWakeUp();
  652. }
  653. // koga klientot ke pristigne, go vika klientot da vleze
  654.  
  655. state.barberCallCustomer();
  656. go.release();
  657.  
  658. enter.acquire();
  659.  
  660. lock.acquire();
  661. --clients;
  662. lock.release();
  663.  
  664. // koga klientot ke vleze, go potstrizuva
  665. state.cutHair();
  666.  
  667. // proveruva dali ima klienti koi cekaat, ako nema, zaspiva
  668.  
  669. lock.acquire();
  670. if (clients == 0) {
  671. state.barberGoToSleep();
  672. sleep = true;
  673. }
  674. lock.release();
  675.  
  676. }
  677. }
  678.  
  679. static class Consumer extends TemplateThread {
  680.  
  681. public Consumer(int numRuns) {
  682. super(numRuns);
  683. }
  684.  
  685. /**
  686. * Da se implementira odnesuvanjeto na ucesnikot spored uslovite na
  687. * zadacata.
  688. */
  689. public void execute() throws InterruptedException {
  690. lock.acquire();
  691. state.customerArrived();
  692. clients++;
  693. if (clients == 5 && sleep) wakeUP.release();
  694. lock.release();
  695.  
  696.  
  697. // dokolku e pettiot, go budi berberot
  698. // koga ke bide povikan, vleguva
  699. go.acquire();
  700. state.customerEntry();
  701. enter.release();
  702.  
  703. // klientot vlegol vo berbernicata i e spremen za potstrizuvanje
  704. // koga ke go potstrizat, plakja
  705. state.customerPay();
  706.  
  707.  
  708. }
  709. }
  710. //<editor-fold defaultstate="collapsed" desc="This is the template code" >
  711. static State state;
  712.  
  713. static class State {
  714.  
  715. private static final Random RANDOM = new Random();
  716. private static final int RANDOM_RANGE = 5;
  717. @SuppressWarnings("unused")
  718. private final int numBarbers;
  719. private boolean barberWaked[];
  720.  
  721. public State(int numBarbers) {
  722. this.numBarbers = numBarbers;
  723. barberWaked = new boolean[numBarbers];
  724. }
  725. private int arrivedCustomers = 0;
  726. private int calledCustomers = 0;
  727. @SuppressWarnings("unused")
  728. private int maxCuttings = 0;
  729. private int numCuttings = 0;
  730.  
  731. public synchronized void customerArrived() throws RuntimeException {
  732. log(null, "customer arrived");
  733. arrivedCustomers++;
  734. }
  735.  
  736. public synchronized void barberWakeUp() throws RuntimeException {
  737. Barber b = (Barber) Thread.currentThread();
  738. if (barberWaked[b.barberId]) {
  739. PointsException e = new PointsException(5, "Berberot e veke buden i nema potreba da se razbudi.");
  740. log(e, null);
  741. } else {
  742. log(null, "the barber is waked up");
  743. barberWaked[b.barberId] = true;
  744. }
  745. }
  746.  
  747. public synchronized void barberCallCustomer() throws RuntimeException {
  748. log(null, "the barber calls the customer");
  749. if (arrivedCustomers <= 0) {
  750. PointsException e = new PointsException(5, "Brojot na klienti koi cekaat e 0 i nema koj da bide povikan.");
  751. log(e, null);
  752. }
  753. calledCustomers++;
  754. }
  755.  
  756. public synchronized void customerEntry() throws RuntimeException {
  757. log(null, "customer sits in the chair");
  758. if (arrivedCustomers <= 0) {
  759. PointsException e = new PointsException(5, "Brojot na klienti koi cekaat e 0 i nema koj da vleze.");
  760. log(e, null);
  761. }
  762. if (calledCustomers <= 0) {
  763. PointsException e = new PointsException(5, "Nema povikano klient i ne moze da vleze.");
  764. log(e, null);
  765. }
  766. arrivedCustomers--;
  767. calledCustomers--;
  768.  
  769. numCuttings++;
  770. }
  771.  
  772. public void cutHair() throws RuntimeException {
  773. synchronized (this) {
  774. if (numCuttings <= 0) {
  775. PointsException e = new PointsException(5, "Nema prisuten klient za potstrizuvanje");
  776. log(e, null);
  777. }
  778.  
  779. log(null, "berber cuts the customer hair");
  780. }
  781. try {
  782. int r;
  783. synchronized (this) {
  784. r = RANDOM.nextInt(RANDOM_RANGE);
  785. }
  786. Thread.sleep(r);
  787. } catch (Exception e) {
  788. //do nothing
  789. }
  790. synchronized (this) {
  791. if (numCuttings <= 0) {
  792. PointsException e = new PointsException(5, "Brojot na klienti koi se strizat e 0 i nema koj da izleze.");
  793. log(e, null);
  794. }
  795. numCuttings--;
  796. }
  797.  
  798. }
  799.  
  800. public synchronized void customerPay() throws RuntimeException {
  801. log(null, "customer is paying and leaving the shop");
  802.  
  803.  
  804. }
  805.  
  806. public synchronized void barberGoToSleep() throws RuntimeException {
  807. Barber b = (Barber) Thread.currentThread();
  808. if (!barberWaked[b.barberId]) {
  809. PointsException e = new PointsException(5, "Berberite veke spijat i ne moze da se prezaspijat.");
  810. log(e, null);
  811. }
  812. if (arrivedCustomers > 0) {
  813. PointsException e = new PointsException(5, "Seuste ima klienti koi cekaat i berberot ne moze da odi na spienje.");
  814. log(e, null);
  815. }
  816. log(null, "all barbers go to sleap");
  817. barberWaked[b.barberId] = false;
  818. }
  819. private List<String> actions = new ArrayList<String>();
  820. @SuppressWarnings("unused")
  821. private List<PointsException> exceptions = new ArrayList<PointsException>();
  822.  
  823. private synchronized void log(PointsException e, String action) {
  824. TemplateThread t = (TemplateThread) Thread.currentThread();
  825. if (e == null) {
  826. actions.add(t.toString() + "\t(a): " + action);
  827. } else {
  828. t.setException(e);
  829. actions.add(t.toString() + "\t(e): " + e.getMessage());
  830. }
  831. }
  832.  
  833. public synchronized void printLog() {
  834. System.out.println("Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
  835. System.out.println("Log na izvrsuvanje na akciite:");
  836. System.out.println("=========================");
  837. System.out.println("tip\tid\titer\takcija/error");
  838. System.out.println("=========================");
  839. for (String l : actions) {
  840. System.out.println(l);
  841. }
  842. }
  843.  
  844. public void printStatus() {
  845. if (!TemplateThread.hasException) {
  846. int poeni = 25;
  847. if (PointsException.getTotalPoints() == 0) {
  848. System.out.println("Procesot e uspesno sinhroniziran. Osvoeni 25 poeni.");
  849. } else {
  850. poeni -= PointsException.getTotalPoints();
  851. PointsException.printErrors();
  852. System.out.println("Osvoeni poeni: " + poeni);
  853. }
  854.  
  855. } else {
  856. System.out.println("Procesot ne e sinhroniziran spored uslovite na zadacata");
  857. printLog();
  858. System.out.println("====================================================");
  859. PointsException.printErrors();
  860. System.out.println("Maksimum Poeni: " + (25 - PointsException.getTotalPoints()));
  861. }
  862.  
  863. }
  864. }
  865.  
  866. abstract static class TemplateThread extends Thread {
  867.  
  868. static boolean hasException = false;
  869. int numRuns = 1;
  870. public int iteration = 0;
  871. @SuppressWarnings("unused")
  872. private Exception exception = null;
  873.  
  874. public TemplateThread(int numRuns) {
  875. this.numRuns = numRuns;
  876. }
  877.  
  878. abstract void execute() throws InterruptedException;
  879.  
  880. @Override
  881. public void run() {
  882. try {
  883. for (int i = 0; i < numRuns && !hasException; i++) {
  884. execute();
  885. iteration++;
  886.  
  887. }
  888. } catch (InterruptedException e) {
  889. // Do nothing
  890. } catch (Exception e) {
  891. exception = e;
  892. hasException = true;
  893. }
  894. }
  895.  
  896. public void setException(Exception exception) {
  897. this.exception = exception;
  898. hasException = true;
  899. }
  900.  
  901. @Override
  902. public String toString() {
  903. Thread current = Thread.currentThread();
  904. if (numRuns > 1) {
  905. return String.format("%s\t%d\t%d", "" + current.getClass().getSimpleName().charAt(0), getId(), iteration);
  906. } else {
  907. return String.format("%s\t%d\t", "" + current.getClass().getSimpleName().charAt(0), getId());
  908. }
  909. }
  910. }
  911.  
  912. @SuppressWarnings("serial")
  913. static class PointsException extends RuntimeException {
  914.  
  915. private static HashMap<String, PointsException> exceptions = new HashMap<String, PointsException>();
  916. private int points;
  917.  
  918. public PointsException(int points, String message) {
  919. super(message);
  920. this.points = points;
  921. exceptions.put(message, this);
  922. }
  923.  
  924. public static int getTotalPoints() {
  925. int sum = 0;
  926. for (PointsException e : exceptions.values()) {
  927. sum += e.getPoints();
  928. }
  929. return sum;
  930. }
  931.  
  932. public static void printErrors() {
  933. System.out.println("Gi imate slednite greski: ");
  934. for (Map.Entry<String, PointsException> e : exceptions.entrySet()) {
  935. System.out.println(String.format("[%s] : (-%d)", e.getKey(), e.getValue().getPoints()));
  936. }
  937. }
  938.  
  939. public int getPoints() {
  940. return points;
  941. }
  942. }
  943.  
  944. public static void main(String[] args) {
  945. try {
  946. start();
  947. } catch (Exception ex) {
  948. ex.printStackTrace();
  949. }
  950. }
  951.  
  952. public static void start() throws Exception {
  953. Scanner s = new Scanner(System.in);
  954. int brBarbers = s.nextInt();
  955. int brKonzumeri = s.nextInt();
  956. int numBarberRuns = s.nextInt();
  957. int numCustomerRuns = s.nextInt();
  958. init(brBarbers);
  959.  
  960. state = new State(brBarbers);
  961. HashSet<Thread> threads = new HashSet<Thread>();
  962.  
  963. for (int i = 0; i < brBarbers; i++) {
  964. Barber prod = new Barber(numBarberRuns, i);
  965. threads.add(prod);
  966. prod.start();
  967. Consumer c = new Consumer(numCustomerRuns);
  968. threads.add(c);
  969. c.start();
  970. }
  971.  
  972. for (int i = 0; i < brKonzumeri / 2 - brBarbers; i++) {
  973. Consumer c = new Consumer(numCustomerRuns);
  974. threads.add(c);
  975. c.start();
  976. }
  977. try {
  978. Thread.sleep(50);
  979. } catch (Exception e) {
  980. //do nothing
  981. }
  982. for (int i = 0; i < brKonzumeri / 2; i++) {
  983. Consumer c = new Consumer(numCustomerRuns);
  984. threads.add(c);
  985. c.start();
  986. }
  987.  
  988.  
  989. for (Thread t : threads) {
  990. t.join(1000);
  991. }
  992.  
  993. for (Thread t : threads) {
  994. if (t.isAlive()) {
  995. t.interrupt();
  996. }
  997. }
  998.  
  999. state.printStatus();
  1000. s.close();
  1001. }
  1002. //</editor-fold>
  1003. }
  1004.  
  1005. __________________________________________________________________________
  1006.  
  1007. // PLEMENSKA VECERA
  1008.  
  1009.  
  1010. import java.util.ArrayList;
  1011. import java.util.HashMap;
  1012. import java.util.HashSet;
  1013. import java.util.List;
  1014. import java.util.Map;
  1015. import java.util.Random;
  1016. import java.util.Scanner;
  1017. import java.util.concurrent.Semaphore;
  1018. import java.util.concurrent.locks.ReentrantLock;
  1019.  
  1020. class TribeDinner {
  1021.  
  1022. public static Semaphore gotvac;
  1023. public static Semaphore zemaHrana;
  1024.  
  1025. public static void init(int numBarbers) {
  1026.  
  1027. gotvac = new Semaphore(1);
  1028. zemaHrana = new Semaphore(3);
  1029.  
  1030. }
  1031.  
  1032. static class TribeMember extends TemplateThread {
  1033.  
  1034. public TribeMember(int numRuns) {
  1035. super(numRuns);
  1036. }
  1037.  
  1038. public void execute() throws InterruptedException {
  1039.  
  1040. gotvac.acquire();
  1041. if (state.isPotEmpty()) {
  1042. state.cook();
  1043. gotvac.release();
  1044. } else {
  1045. gotvac.release();
  1046. zemaHrana.acquire();
  1047. state.fillPlate();
  1048. zemaHrana.release();
  1049. state.eat();
  1050. }
  1051.  
  1052. }
  1053. }
  1054.  
  1055. // <editor-fold defaultstate="collapsed" desc="This is the template code" >
  1056. static State state;
  1057.  
  1058. static class State {
  1059.  
  1060. private static final String _10_JADENJETO_NE_E_PARALELIZIRANO = "jadenjeto ne e paralelizirano. Site jadat eden po eden";
  1061. 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.";
  1062.  
  1063. private static final String _10_DVAJCA_ISTOVREMENO_PROVERUVAAT = "Dvajca istovremeno proveruvaat dali kazanot e prazen. Maksimum eden e dozvoleno.";
  1064. private static final String _7_NEMA_MESTO_POKRAJ_KAZANOT = "Nema mesto pokraj kazanot. Maksimum tri clena moze da zemaat hrana istovremeno.";
  1065. 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()'";
  1066. 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";
  1067.  
  1068. private static final Random RANDOM = new Random();
  1069. private static final int POT_CAPACITY = 15;
  1070.  
  1071. private LimitedCounter platesLeft = new LimitedCounter(0, null, 0, null, 0, 5,
  1072. _5_NE_MOZE_DA_JADE_OD_PRAZEN_KAZAN);
  1073.  
  1074. private LimitedCounter checks = new LimitedCounter(0, 1, 10, _10_DVAJCA_ISTOVREMENO_PROVERUVAAT, null, 0, null);
  1075.  
  1076. private LimitedCounter fills = new LimitedCounter(0, 3, 7, _7_NEMA_MESTO_POKRAJ_KAZANOT, null, 0, null);
  1077.  
  1078. private LimitedCounter eat = new LimitedCounter(0);
  1079.  
  1080. public State() {
  1081.  
  1082. }
  1083.  
  1084. public boolean isPotEmpty() throws RuntimeException {
  1085. log(checks.incrementWithMax(), "proverka dali ima hrana vo kazanot");
  1086. sleep(5);
  1087. boolean res = platesLeft.getValue() == 0;
  1088. log(checks.decrementWithMin(), null);
  1089. return res;
  1090. }
  1091.  
  1092. public void fillPlate() throws RuntimeException {
  1093. log(fills.incrementWithMax(), "zemanje na hrana");
  1094. log(platesLeft.decrementWithMin(), null);
  1095. sleep(5);
  1096. log(platesLeft.incrementWithMax(), null);
  1097. log(fills.decrementWithMin(), null);
  1098. }
  1099.  
  1100. public void eat() throws RuntimeException {
  1101. log(eat.incrementWithMax(), "jadenje");
  1102. sleep(10);
  1103. log(eat.decrementWithMin(), null);
  1104. }
  1105.  
  1106. public void cook() throws RuntimeException {
  1107. synchronized (State.class) {
  1108. if (platesLeft.getValue() == 0) {
  1109. platesLeft.setValue(POT_CAPACITY);
  1110. } else {
  1111. PointsException e = new PointsException(5, _5_NE_MOZE_DA_SE_GOTVI_VO_KAZAN_KOJ_NE_E_PRAZEN);
  1112. log(e, null);
  1113. }
  1114. }
  1115. }
  1116.  
  1117. public void finalize() {
  1118. if (fills.getMax() == 1) {
  1119. logException(new PointsException(10, _10_PRISTAPOT_DO_KAZANOT_NE_E_PARALELIZIRAN));
  1120. }
  1121. if (eat.getMax() == 1) {
  1122. logException(new PointsException(10, _10_JADENJETO_NE_E_PARALELIZIRANO));
  1123. }
  1124. }
  1125.  
  1126. private List<String> actions = new ArrayList<String>();
  1127.  
  1128. private void sleep(int range) {
  1129. try {
  1130. Thread.sleep(RANDOM.nextInt(range));
  1131. } catch (InterruptedException e) {
  1132. }
  1133. }
  1134.  
  1135. protected TemplateThread getThread() {
  1136. TemplateThread t = (TemplateThread) Thread.currentThread();
  1137. return t;
  1138. }
  1139.  
  1140. private synchronized void log(PointsException e, String action) {
  1141. TemplateThread t = (TemplateThread) Thread.currentThread();
  1142. if (e != null) {
  1143. t.setException(e);
  1144. actions.add(t.toString() + "\t(e): " + e.getMessage());
  1145. } else if (action != null) {
  1146. actions.add(t.toString() + "\t(a): " + action);
  1147. }
  1148. }
  1149.  
  1150. private synchronized void logException(PointsException e) {
  1151. actions.add("\t(e): " + e.getMessage());
  1152. }
  1153.  
  1154. public synchronized void printLog() {
  1155. System.out.println(
  1156. "Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
  1157. System.out.println("Log na izvrsuvanje na akciite:");
  1158. System.out.println("=========================");
  1159. System.out.println("tip\tid\titer\takcija/error");
  1160. System.out.println("=========================");
  1161. for (String l : actions) {
  1162. System.out.println(l);
  1163. }
  1164. }
  1165.  
  1166. public void printStatus() {
  1167. finalize();
  1168. if (!TemplateThread.hasException) {
  1169. int poeni = 25;
  1170. if (PointsException.getTotalPoints() == 0) {
  1171. System.out.println("Procesot e uspesno sinhroniziran. Osvoeni 25 poeni.");
  1172. } else {
  1173. poeni -= PointsException.getTotalPoints();
  1174. PointsException.printErrors();
  1175. System.out.println("Maksimalni osvoeni poeni: " + poeni);
  1176. }
  1177.  
  1178. } else {
  1179. System.out.println("Procesot ne e sinhroniziran spored uslovite na zadacata");
  1180. printLog();
  1181. System.out.println("====================================================");
  1182. PointsException.printErrors();
  1183. int total = (25 - PointsException.getTotalPoints());
  1184. if (total < 0) {
  1185. total = 0;
  1186. }
  1187. System.out.println("Maksimum Poeni: " + total);
  1188. }
  1189.  
  1190. }
  1191. }
  1192.  
  1193. static class LimitedCounter {
  1194.  
  1195. private int value;
  1196. private Integer maxAllowed;
  1197. private Integer minAllowed;
  1198. private int maxErrorPoints;
  1199. private int minErrorPoints;
  1200. private String maxErrorMessage;
  1201. private String minErrorMessage;
  1202.  
  1203. private int max;
  1204.  
  1205. public LimitedCounter(int value) {
  1206. super();
  1207. this.value = value;
  1208. this.max = value;
  1209. }
  1210.  
  1211. public LimitedCounter(int value, Integer maxAllowed, int maxErrorPoints, String maxErrorMessage,
  1212. Integer minAllowed, int minErrorPoints, String minErrorMessage) {
  1213. super();
  1214. this.value = value;
  1215. this.max = value;
  1216. this.maxAllowed = maxAllowed;
  1217. this.minAllowed = minAllowed;
  1218. this.maxErrorPoints = maxErrorPoints;
  1219. this.minErrorPoints = minErrorPoints;
  1220. this.maxErrorMessage = maxErrorMessage;
  1221. this.minErrorMessage = minErrorMessage;
  1222. }
  1223.  
  1224. public int getMax() {
  1225. return max;
  1226. }
  1227.  
  1228. public int getValue() {
  1229. return value;
  1230. }
  1231.  
  1232. public void setValue(int value) {
  1233. this.value = value;
  1234. }
  1235.  
  1236. public PointsException incrementWithMax() {
  1237. synchronized (LimitedCounter.class) {
  1238. value++;
  1239. if (value > max) {
  1240. max = value;
  1241. }
  1242. if (maxAllowed != null) {
  1243. if (value > maxAllowed) {
  1244. PointsException e = new PointsException(maxErrorPoints, maxErrorMessage);
  1245. return e;
  1246. }
  1247. }
  1248. }
  1249. return null;
  1250. }
  1251.  
  1252. public PointsException decrementWithMin() {
  1253. synchronized (LimitedCounter.class) {
  1254. value--;
  1255. if (minAllowed != null) {
  1256. if (value < minAllowed) {
  1257. PointsException e = new PointsException(minErrorPoints, minErrorMessage);
  1258. return e;
  1259. }
  1260. }
  1261. }
  1262. return null;
  1263. }
  1264. }
  1265.  
  1266. abstract static class TemplateThread extends Thread {
  1267.  
  1268. static boolean hasException = false;
  1269. int numRuns = 1;
  1270. public int iteration = 0;
  1271. protected Exception exception = null;
  1272.  
  1273. public TemplateThread(int numRuns) {
  1274. this.numRuns = numRuns;
  1275. }
  1276.  
  1277. abstract void execute() throws InterruptedException;
  1278.  
  1279. @Override
  1280. public void run() {
  1281. try {
  1282. for (int i = 0; i < numRuns&&!hasException; i++) {
  1283. execute();
  1284. iteration++;
  1285.  
  1286. }
  1287. } catch (InterruptedException e) {
  1288. // Do nothing
  1289. } catch (Exception e) {
  1290. exception = e;
  1291. hasException = true;
  1292. }
  1293. }
  1294.  
  1295. public void setException(Exception exception) {
  1296. this.exception = exception;
  1297. hasException = true;
  1298. }
  1299.  
  1300. @Override
  1301. public String toString() {
  1302. Thread current = Thread.currentThread();
  1303. if (numRuns > 1) {
  1304. return String.format("%s\t%d\t%d", "" + current.getClass().getSimpleName().charAt(0), getId(),
  1305. iteration);
  1306. } else {
  1307. return String.format("%s\t%d\t", "" + current.getClass().getSimpleName().charAt(0), getId());
  1308. }
  1309. }
  1310. }
  1311.  
  1312. static class PointsException extends RuntimeException {
  1313.  
  1314. private static HashMap<String, PointsException> exceptions = new HashMap<String, PointsException>();
  1315. private int points;
  1316.  
  1317. public PointsException(int points, String message) {
  1318. super(message);
  1319. this.points = points;
  1320. exceptions.put(message, this);
  1321. }
  1322.  
  1323. public static int getTotalPoints() {
  1324. int sum = 0;
  1325. for (PointsException e : exceptions.values()) {
  1326. sum += e.getPoints();
  1327. }
  1328. return sum;
  1329. }
  1330.  
  1331. public static void printErrors() {
  1332. System.out.println("Gi imate slednite greski: ");
  1333. for (Map.Entry<String, PointsException> e : exceptions.entrySet()) {
  1334. System.out.println(String.format("[%s] : (-%d)", e.getKey(), e.getValue().getPoints()));
  1335. }
  1336. }
  1337.  
  1338. public int getPoints() {
  1339. return points;
  1340. }
  1341. }
  1342.  
  1343. public static void main(String[] args) {
  1344. try {
  1345. start();
  1346. } catch (Exception ex) {
  1347. ex.printStackTrace();
  1348. }
  1349. }
  1350.  
  1351. public static void start() throws Exception {
  1352. Scanner s = new Scanner(System.in);
  1353. int brKonzumeri = s.nextInt();
  1354. int numCustomerRuns = s.nextInt();
  1355. init(brKonzumeri);
  1356.  
  1357. state = new State();
  1358. HashSet<Thread> threads = new HashSet<Thread>();
  1359.  
  1360. for (int i = 0; i < brKonzumeri; i++) {
  1361. TribeMember c = new TribeMember(numCustomerRuns);
  1362. threads.add(c);
  1363. c.start();
  1364. }
  1365. try {
  1366. Thread.sleep(50);
  1367. } catch (Exception e) {
  1368. // do nothing
  1369. }
  1370.  
  1371. for (Thread t : threads) {
  1372. t.join(1000);
  1373. }
  1374.  
  1375. for (Thread t : threads) {
  1376. if (t.isAlive()) {
  1377. t.interrupt();
  1378. if (t instanceof TemplateThread) {
  1379. TemplateThread tt = (TemplateThread) t;
  1380. tt.setException(new PointsException(25, "DEADLOCK"));
  1381. }
  1382. }
  1383. }
  1384. s.close();
  1385. state.printStatus();
  1386. }
  1387. // </editor-fold>
  1388. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement