Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // JAVA IO PRVA GRUPA
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FilenameFilter;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- import java.util.ArrayList;
- public class ExamIO {
- public static void main(String[] args) throws IOException {
- moveWritableTxtFiles(args[0], args[1]);
- invertLargeFile(args[2], args[5]);
- }
- private static void moveWritableTxtFiles(String from, String to) {
- File fromFolder = new File(from);
- File toFolder = new File(to);
- if (!fromFolder.exists()) {
- System.out.println("Ne postoi");
- }
- if (!toFolder.exists()) {
- toFolder.mkdirs();
- }
- FilenameFilter filter = new FilenameFilter() {
- @Override
- public boolean accept(File arg0, String arg1) {
- return arg1.toLowerCase().endsWith(".txt");
- }
- };
- File[] files = fromFolder.listFiles(filter);
- for (File f : files) {
- if (f.canWrite()) {
- f.renameTo(toFolder);
- }
- }
- }
- @SuppressWarnings({ "unused", "resource" })
- private static void deserializeData(String source, ArrayList<byte[]> data, long elementLength) throws IOException {
- // RandomAccessFile read = new RandomAccessFile(source,"r");
- // byte[] niza = new byte[(int)elementLength];
- // read.seek(0);
- // while((read.read(niza,0,(int) elementLength))!=-1)
- // {
- // data.add(niza);
- // niza = new byte[(int)elementLength];
- // }
- FileInputStream in = new FileInputStream(source);
- byte[] buffer = new byte[(int) elementLength];
- while (in.read(buffer) != -1) {
- data.add(buffer);
- buffer = new byte[(int) elementLength];
- }
- }
- private static void invertLargeFile(String source, String destination) throws IOException {
- File izvor = new File(source);
- File destinacija = new File(destination);
- RandomAccessFile read = null;
- RandomAccessFile write = null;
- try {
- read = new RandomAccessFile(izvor, "r");
- write = new RandomAccessFile(destinacija, "rw");
- for (int i = (int) (read.length() - 1); i >= 0; i--) {
- read.seek(i);
- write.writeByte(read.readByte());
- }
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- if (read != null) {
- read.close();
- }
- if (write != null) {
- write.close();
- }
- }
- }
- }
- _______________________________________________________________________________
- // JAVA IO VTORA GRUPA
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.FilenameFilter;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.io.RandomAccessFile;
- import java.util.ArrayList;
- class ExamIO2 {
- public static void main(String[] args) throws IOException {
- long size = Long.parseLong(args[2]);
- copyLargeTxtFiles(args[0], args[1], size);
- long position = 6;// Long.parseLong(args[3]);
- long elementLength = 6;// Long.parseLong(args[4]);
- String destination = "C:\\Users\\Tech\\Desktop\\destinacija.txt";
- ArrayList<byte[]> data = new ArrayList<byte[]>();
- serializeData(destination, data);
- deserializeDataAtPosition("C:\\Users\\Tech\\Desktop\\izvor.jpg", position, elementLength);
- }
- @SuppressWarnings({ "resource" })
- private static void serializeData(String destination, ArrayList<byte[]> data) throws IOException {
- OutputStream out = new FileOutputStream(destination);
- for(byte[] b : data)
- {
- out.write(b);
- }
- }
- @SuppressWarnings("resource")
- private static byte[] deserializeDataAtPosition(String source, long position, long elementLength)
- throws IOException {
- byte[] niza = new byte[(int) elementLength];
- RandomAccessFile read = new RandomAccessFile(source, "r");
- read.seek(((position - 1) * elementLength));
- read.read(niza, 0, (int) elementLength);
- for (byte b : niza) {
- System.out.print(b);
- }
- return niza;
- }
- private static void copyLargeTxtFiles(String from, String to, long size) throws IOException {
- File fromFolder = new File(from);
- File toFolder = new File(to);
- if (!fromFolder.exists()) {
- System.out.println("Ne postoi");
- }
- if (!toFolder.exists()) {
- toFolder.mkdirs();
- }
- FilenameFilter filter = new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return name.toLowerCase().endsWith(".txt");
- }
- };
- File[] files = fromFolder.listFiles(filter);
- for (File f : files) {
- if (f.length() > size) {
- File copy = copyText(f);
- copy.renameTo(toFolder);
- }
- }
- }
- @SuppressWarnings("resource")
- private static File copyText(File fromFolder) throws IOException {
- File copy = new File(fromFolder.getParentFile() + "\\copyOf" + fromFolder.getName());
- BufferedReader br = new BufferedReader(new FileReader(fromFolder));
- BufferedWriter bw = new BufferedWriter(new FileWriter(copy));
- String line = null;
- while ((line = br.readLine()) != null) {
- bw.write(line);
- bw.flush();
- }
- bw.close();
- return copy;
- }
- }
- ___________________________________________________________________________________
- // JAVA IO JUNSKA SESIJA
- package junskaSesija;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FilenameFilter;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- public class JunskaIO {
- public static void main(String[] args) throws IOException {
- String in = args[0];
- String out = args[1];
- manage(in, out);
- }
- private static void manage(String in, String out) throws IOException {
- // TODO Auto-generated method stub
- FilenameFilter filter = new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- // TODO Auto-generated method stub
- return name.toLowerCase().endsWith(".dat");
- }
- };
- File source = new File(in);
- File destination = new File(out);
- File resources = new File("C:\\Users\\Tech\\Desktop\\resource\\writable-content.txt");
- if (!source.exists()) {
- System.out.println("Ne postoi");
- }
- if (destination.exists()) {
- File[] files = destination.listFiles();
- for (File f : files) {
- f.delete();
- }
- }
- if (!destination.exists()) {
- destination.mkdirs();
- }
- File[] file = source.listFiles(filter);
- for (File f : file) {
- if (f.canWrite()) {
- f.renameTo(destination);
- System.out.println("Pomestuvam " + f.getAbsolutePath());
- }
- if (!f.canWrite()) {
- RandomAccessFile read = new RandomAccessFile(f, "r");
- RandomAccessFile write = new RandomAccessFile(resources, "rw");
- for (int i = 0; i < read.length(); i++) {
- read.seek(i);
- write.writeByte(read.readByte());
- System.out.println("Dopisuvam " + f.getAbsolutePath());
- }
- // String line = null;
- // while((line = read.readLine())!=null)
- // {
- // write.writeBytes(line);
- // }
- }
- if (f.isHidden()) {
- f.delete();
- System.out.println("Zbunet sum");
- }
- }
- }
- }
- ____________________________________________________________________________
- // TANC SO STUDENTITE
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Random;
- import java.util.concurrent.Semaphore;
- public class TancSoStudentite {
- // TODO: Definicija na globalni promenlivi i semafori
- public static Semaphore maski;
- public static Semaphore zenski;
- public static Semaphore spremna;
- public static Semaphore parovi;
- public void init() {
- // TODO: da se implementira
- maski = new Semaphore(10);
- zenski = new Semaphore(10);
- spremna = new Semaphore(0);
- parovi = new Semaphore(3);
- }
- class Masko extends Thread {
- // TODO: Definicija na promenlivi za sostojbata
- public void ucestvo() throws InterruptedException {
- // TODO: da se implementira
- maski.acquire();
- show.presobleci();
- maski.release();
- spremna.acquire();
- parovi.acquire();
- show.tancuvaj();
- parovi.release();
- }
- @Override
- public void run() {
- try {
- ucestvo();
- } catch (InterruptedException e) {
- // Do nothing
- } catch (Exception e) {
- exception = e;
- hasException = true;
- }
- }
- @Override
- public String toString() {
- return String.format("m\t%d", getId());
- }
- public Exception exception = null;
- }
- class Zensko extends Thread {
- // TODO: Definicija na promenlivi za sostojbata
- public void ucestvo() throws InterruptedException {
- // TODO: da se implementira
- zenski.acquire();
- show.presobleci();
- zenski.release();
- spremna.release();
- }
- @Override
- public void run() {
- try {
- ucestvo();
- } catch (InterruptedException e) {
- // Do nothing
- } catch (Exception e) {
- exception = e;
- hasException = true;
- }
- }
- @Override
- public String toString() {
- return String.format("z\t%d", getId());
- }
- public Exception exception = null;
- }
- public static void main(String[] args) {
- try {
- TancSoStudentite environment = new TancSoStudentite();
- environment.start();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- public void start() throws Exception {
- show = new Show();
- init();
- HashSet<Thread> threads = new HashSet<Thread>();
- for (int i = 0; i < BROJ_INSTANCI; i++) {
- Zensko z = new Zensko();
- Masko m = new Masko();
- threads.add(z);
- threads.add(m);
- }
- for (Thread t : threads) {
- t.start();
- }
- boolean valid = true;
- for (Thread t : threads) {
- if (!hasException) {
- t.join();
- } else {
- t.interrupt();
- }
- }
- show.printStatus();
- }
- public class Show {
- public static final int BROJ_GARDEROBA = 10;
- public static final int BROJ_TEREN = 3;
- public static final int TYPE_MASKO = 1;
- public static final int TYPE_ZENSKO = 2;
- public static final int TYPE_UNKNOWN = -1;
- public Show() {
- }
- public int brojMaskiGarderoba = 0;
- public int brojZenskiGarderoba = 0;
- public int brojTancuvanja = 0;
- public int maxMaskiGarderoba = 0;
- public int maxZenskiGarderoba = 0;
- public int maxTancuvanja = 0;
- public void presobleci() throws RuntimeException {
- log(null, "presobleci start");
- Thread t = Thread.currentThread();
- if (t instanceof Masko) {
- synchronized (RANDOM) {
- brojMaskiGarderoba++;
- if (brojMaskiGarderoba > 10) {
- exception("Ne moze da ima poveke od 10 maski vo maskata garderoba.");
- }
- if (brojMaskiGarderoba > maxMaskiGarderoba) {
- maxMaskiGarderoba = brojMaskiGarderoba;
- }
- }
- waitRandom();
- synchronized (RANDOM) {
- brojMaskiGarderoba--;
- }
- } else {
- synchronized (RANDOM) {
- brojZenskiGarderoba++;
- if (brojZenskiGarderoba > 10) {
- exception("Ne moze da ima poveke od 10 zenski vo zenskata garderoba.");
- }
- if (brojZenskiGarderoba > maxZenskiGarderoba) {
- maxZenskiGarderoba = brojZenskiGarderoba;
- }
- }
- waitRandom();
- synchronized (RANDOM) {
- brojZenskiGarderoba--;
- }
- }
- log(null, "presobleci kraj");
- }
- public void tancuvaj() throws RuntimeException {
- log(null, "tancuvaj start");
- synchronized (RANDOM) {
- brojTancuvanja++;
- if (brojTancuvanja > BROJ_TEREN) {
- exception("Ne moze paralelno da tancuvaat poveke od 3 para.");
- }
- if (brojTancuvanja > maxTancuvanja) {
- maxTancuvanja = brojTancuvanja;
- }
- }
- waitRandom();
- synchronized (RANDOM) {
- brojTancuvanja--;
- }
- log(null, "tancuvaj kraj");
- }
- private void waitRandom() {
- try {
- int r;
- synchronized (RANDOM) {
- r = RANDOM.nextInt(RANDOM_RANGE);
- }
- Thread.sleep(r);
- } catch (Exception e) {
- // do nothing
- }
- }
- private void exception(String message) {
- RuntimeException e = new RuntimeException(message);
- log(e, null);
- hasError = true;
- throw e;
- }
- public int getType() {
- Thread t = Thread.currentThread();
- if (t instanceof Masko) {
- return TYPE_MASKO;
- } else if (t instanceof Zensko) {
- return TYPE_ZENSKO;
- } else {
- return TYPE_UNKNOWN;
- }
- }
- private synchronized void log(RuntimeException e, String action) {
- Thread t = Thread.currentThread();
- if (e == null) {
- actions.add(t.toString() + "\t(a): " + action);
- } else {
- actions.add(t.toString() + "\t(e): " + e.getMessage());
- }
- }
- public synchronized void printLog() {
- System.out.println(
- "Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
- System.out.println("Log na izvrsuvanje na akciite:");
- System.out.println("=========================");
- System.out.println("(tip m<=>Masko, tip z<=>Zensko)");
- System.out.println("tip\tid\takcija/error");
- System.out.println("=========================");
- for (String l : actions) {
- System.out.println(l);
- }
- }
- public void printStatus() {
- if (!hasError) {
- int poeni = 25;
- System.out.println("Procesot e uspesno sinhroniziran");
- if (show.maxMaskiGarderoba == 1 || show.maxZenskiGarderoba == 1) {
- System.out.println("\t-no ima maksimum eden ucesnik vo garderobata.");
- poeni -= 5;
- }
- if (show.maxTancuvanja == 1) {
- System.out.println("\t-no ima maksimum edna proverka vo eden moment.");
- poeni -= 5;
- }
- System.out.println("Osvoeni poeni: " + poeni);
- } else {
- System.out.println("Procesot ne e sinhroniziran spored uslovite na zadacata");
- show.printLog();
- System.out.println("Maksimum mozni poeni: 15");
- }
- }
- private List<String> actions = new ArrayList<String>();
- private boolean hasError = false;
- }
- // Konstanti
- public static int BROJ_INSTANCI = 1000;
- public static final Random RANDOM = new Random();
- public static final int RANDOM_RANGE = 3;
- // Instanca od bafferot
- public Show show;
- public boolean hasException = false;
- }
- ___________________________________________________________________________________
- // ZASPAN BERBER
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Map;
- import java.util.Random;
- import java.util.Scanner;
- import java.util.concurrent.Semaphore;
- /**
- *
- * @author ristes
- */
- public class TemplateNumRunsAndNumInstances {
- //TODO: definirajte gi semaforite i ostanatite promenlivi ovde (mora site da se static)
- static Semaphore wakeUP;
- static Semaphore lock;
- static Semaphore enter;
- static Semaphore go;
- static boolean sleep;
- static int clients;
- /**
- * Metod koj treba da gi inicijalizira vrednostite na semaforite i
- * ostanatite promenlivi za sinhronizacija.
- *
- *
- * TODO: da se implementira
- *
- */
- public static void init(int numBarbers) {
- wakeUP = new Semaphore(0);
- lock = new Semaphore(1);
- go = new Semaphore(0);
- enter = new Semaphore(0);
- clients = 0;
- sleep = true;
- }
- static class Barber extends TemplateThread {
- public int barberId;
- public Barber(int numRuns, int barberId) {
- super(numRuns);
- this.barberId = barberId;
- }
- /**
- * Da se implementira odnesuvanjeto na berberot spored baranjeto na
- * zadacata.
- *
- *
- * TODO: da se implementira
- *
- */
- public void execute() throws InterruptedException {
- // koga 5tiot klient ke notificira, berberot treba da se razbudi
- if (sleep) {
- wakeUP.acquire();
- sleep = false;
- state.barberWakeUp();
- }
- // koga klientot ke pristigne, go vika klientot da vleze
- state.barberCallCustomer();
- go.release();
- enter.acquire();
- lock.acquire();
- --clients;
- lock.release();
- // koga klientot ke vleze, go potstrizuva
- state.cutHair();
- // proveruva dali ima klienti koi cekaat, ako nema, zaspiva
- lock.acquire();
- if (clients == 0) {
- state.barberGoToSleep();
- sleep = true;
- }
- lock.release();
- }
- }
- static class Consumer extends TemplateThread {
- public Consumer(int numRuns) {
- super(numRuns);
- }
- /**
- * Da se implementira odnesuvanjeto na ucesnikot spored uslovite na
- * zadacata.
- */
- public void execute() throws InterruptedException {
- lock.acquire();
- state.customerArrived();
- clients++;
- if (clients == 5 && sleep) wakeUP.release();
- lock.release();
- // dokolku e pettiot, go budi berberot
- // koga ke bide povikan, vleguva
- go.acquire();
- state.customerEntry();
- enter.release();
- // klientot vlegol vo berbernicata i e spremen za potstrizuvanje
- // koga ke go potstrizat, plakja
- state.customerPay();
- }
- }
- //<editor-fold defaultstate="collapsed" desc="This is the template code" >
- static State state;
- static class State {
- private static final Random RANDOM = new Random();
- private static final int RANDOM_RANGE = 5;
- @SuppressWarnings("unused")
- private final int numBarbers;
- private boolean barberWaked[];
- public State(int numBarbers) {
- this.numBarbers = numBarbers;
- barberWaked = new boolean[numBarbers];
- }
- private int arrivedCustomers = 0;
- private int calledCustomers = 0;
- @SuppressWarnings("unused")
- private int maxCuttings = 0;
- private int numCuttings = 0;
- public synchronized void customerArrived() throws RuntimeException {
- log(null, "customer arrived");
- arrivedCustomers++;
- }
- public synchronized void barberWakeUp() throws RuntimeException {
- Barber b = (Barber) Thread.currentThread();
- if (barberWaked[b.barberId]) {
- PointsException e = new PointsException(5, "Berberot e veke buden i nema potreba da se razbudi.");
- log(e, null);
- } else {
- log(null, "the barber is waked up");
- barberWaked[b.barberId] = true;
- }
- }
- public synchronized void barberCallCustomer() throws RuntimeException {
- log(null, "the barber calls the customer");
- if (arrivedCustomers <= 0) {
- PointsException e = new PointsException(5, "Brojot na klienti koi cekaat e 0 i nema koj da bide povikan.");
- log(e, null);
- }
- calledCustomers++;
- }
- public synchronized void customerEntry() throws RuntimeException {
- log(null, "customer sits in the chair");
- if (arrivedCustomers <= 0) {
- PointsException e = new PointsException(5, "Brojot na klienti koi cekaat e 0 i nema koj da vleze.");
- log(e, null);
- }
- if (calledCustomers <= 0) {
- PointsException e = new PointsException(5, "Nema povikano klient i ne moze da vleze.");
- log(e, null);
- }
- arrivedCustomers--;
- calledCustomers--;
- numCuttings++;
- }
- public void cutHair() throws RuntimeException {
- synchronized (this) {
- if (numCuttings <= 0) {
- PointsException e = new PointsException(5, "Nema prisuten klient za potstrizuvanje");
- log(e, null);
- }
- log(null, "berber cuts the customer hair");
- }
- try {
- int r;
- synchronized (this) {
- r = RANDOM.nextInt(RANDOM_RANGE);
- }
- Thread.sleep(r);
- } catch (Exception e) {
- //do nothing
- }
- synchronized (this) {
- if (numCuttings <= 0) {
- PointsException e = new PointsException(5, "Brojot na klienti koi se strizat e 0 i nema koj da izleze.");
- log(e, null);
- }
- numCuttings--;
- }
- }
- public synchronized void customerPay() throws RuntimeException {
- log(null, "customer is paying and leaving the shop");
- }
- public synchronized void barberGoToSleep() throws RuntimeException {
- Barber b = (Barber) Thread.currentThread();
- if (!barberWaked[b.barberId]) {
- PointsException e = new PointsException(5, "Berberite veke spijat i ne moze da se prezaspijat.");
- log(e, null);
- }
- if (arrivedCustomers > 0) {
- PointsException e = new PointsException(5, "Seuste ima klienti koi cekaat i berberot ne moze da odi na spienje.");
- log(e, null);
- }
- log(null, "all barbers go to sleap");
- barberWaked[b.barberId] = false;
- }
- private List<String> actions = new ArrayList<String>();
- @SuppressWarnings("unused")
- private List<PointsException> exceptions = new ArrayList<PointsException>();
- private synchronized void log(PointsException e, String action) {
- TemplateThread t = (TemplateThread) Thread.currentThread();
- if (e == null) {
- actions.add(t.toString() + "\t(a): " + action);
- } else {
- t.setException(e);
- actions.add(t.toString() + "\t(e): " + e.getMessage());
- }
- }
- public synchronized void printLog() {
- System.out.println("Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
- System.out.println("Log na izvrsuvanje na akciite:");
- System.out.println("=========================");
- System.out.println("tip\tid\titer\takcija/error");
- System.out.println("=========================");
- for (String l : actions) {
- System.out.println(l);
- }
- }
- public void printStatus() {
- if (!TemplateThread.hasException) {
- int poeni = 25;
- if (PointsException.getTotalPoints() == 0) {
- System.out.println("Procesot e uspesno sinhroniziran. Osvoeni 25 poeni.");
- } else {
- poeni -= PointsException.getTotalPoints();
- PointsException.printErrors();
- System.out.println("Osvoeni poeni: " + poeni);
- }
- } else {
- System.out.println("Procesot ne e sinhroniziran spored uslovite na zadacata");
- printLog();
- System.out.println("====================================================");
- PointsException.printErrors();
- System.out.println("Maksimum Poeni: " + (25 - PointsException.getTotalPoints()));
- }
- }
- }
- abstract static class TemplateThread extends Thread {
- static boolean hasException = false;
- int numRuns = 1;
- public int iteration = 0;
- @SuppressWarnings("unused")
- private Exception exception = null;
- public TemplateThread(int numRuns) {
- this.numRuns = numRuns;
- }
- abstract void execute() throws InterruptedException;
- @Override
- public void run() {
- try {
- for (int i = 0; i < numRuns && !hasException; i++) {
- execute();
- iteration++;
- }
- } catch (InterruptedException e) {
- // Do nothing
- } catch (Exception e) {
- exception = e;
- hasException = true;
- }
- }
- public void setException(Exception exception) {
- this.exception = exception;
- hasException = true;
- }
- @Override
- public String toString() {
- Thread current = Thread.currentThread();
- if (numRuns > 1) {
- return String.format("%s\t%d\t%d", "" + current.getClass().getSimpleName().charAt(0), getId(), iteration);
- } else {
- return String.format("%s\t%d\t", "" + current.getClass().getSimpleName().charAt(0), getId());
- }
- }
- }
- @SuppressWarnings("serial")
- static class PointsException extends RuntimeException {
- private static HashMap<String, PointsException> exceptions = new HashMap<String, PointsException>();
- private int points;
- public PointsException(int points, String message) {
- super(message);
- this.points = points;
- exceptions.put(message, this);
- }
- public static int getTotalPoints() {
- int sum = 0;
- for (PointsException e : exceptions.values()) {
- sum += e.getPoints();
- }
- return sum;
- }
- public static void printErrors() {
- System.out.println("Gi imate slednite greski: ");
- for (Map.Entry<String, PointsException> e : exceptions.entrySet()) {
- System.out.println(String.format("[%s] : (-%d)", e.getKey(), e.getValue().getPoints()));
- }
- }
- public int getPoints() {
- return points;
- }
- }
- public static void main(String[] args) {
- try {
- start();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- public static void start() throws Exception {
- Scanner s = new Scanner(System.in);
- int brBarbers = s.nextInt();
- int brKonzumeri = s.nextInt();
- int numBarberRuns = s.nextInt();
- int numCustomerRuns = s.nextInt();
- init(brBarbers);
- state = new State(brBarbers);
- HashSet<Thread> threads = new HashSet<Thread>();
- for (int i = 0; i < brBarbers; i++) {
- Barber prod = new Barber(numBarberRuns, i);
- threads.add(prod);
- prod.start();
- Consumer c = new Consumer(numCustomerRuns);
- threads.add(c);
- c.start();
- }
- for (int i = 0; i < brKonzumeri / 2 - brBarbers; i++) {
- Consumer c = new Consumer(numCustomerRuns);
- threads.add(c);
- c.start();
- }
- try {
- Thread.sleep(50);
- } catch (Exception e) {
- //do nothing
- }
- for (int i = 0; i < brKonzumeri / 2; i++) {
- Consumer c = new Consumer(numCustomerRuns);
- threads.add(c);
- c.start();
- }
- for (Thread t : threads) {
- t.join(1000);
- }
- for (Thread t : threads) {
- if (t.isAlive()) {
- t.interrupt();
- }
- }
- state.printStatus();
- s.close();
- }
- //</editor-fold>
- }
- __________________________________________________________________________
- // PLEMENSKA VECERA
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Map;
- import java.util.Random;
- import java.util.Scanner;
- import java.util.concurrent.Semaphore;
- import java.util.concurrent.locks.ReentrantLock;
- class TribeDinner {
- public static Semaphore gotvac;
- public static Semaphore zemaHrana;
- public static void init(int numBarbers) {
- gotvac = new Semaphore(1);
- zemaHrana = new Semaphore(3);
- }
- static class TribeMember extends TemplateThread {
- public TribeMember(int numRuns) {
- super(numRuns);
- }
- public void execute() throws InterruptedException {
- gotvac.acquire();
- if (state.isPotEmpty()) {
- state.cook();
- gotvac.release();
- } else {
- gotvac.release();
- zemaHrana.acquire();
- state.fillPlate();
- zemaHrana.release();
- state.eat();
- }
- }
- }
- // <editor-fold defaultstate="collapsed" desc="This is the template code" >
- static State state;
- static class State {
- private static final String _10_JADENJETO_NE_E_PARALELIZIRANO = "jadenjeto ne e paralelizirano. Site jadat eden po eden";
- 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.";
- private static final String _10_DVAJCA_ISTOVREMENO_PROVERUVAAT = "Dvajca istovremeno proveruvaat dali kazanot e prazen. Maksimum eden e dozvoleno.";
- private static final String _7_NEMA_MESTO_POKRAJ_KAZANOT = "Nema mesto pokraj kazanot. Maksimum tri clena moze da zemaat hrana istovremeno.";
- 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()'";
- 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";
- private static final Random RANDOM = new Random();
- private static final int POT_CAPACITY = 15;
- private LimitedCounter platesLeft = new LimitedCounter(0, null, 0, null, 0, 5,
- _5_NE_MOZE_DA_JADE_OD_PRAZEN_KAZAN);
- private LimitedCounter checks = new LimitedCounter(0, 1, 10, _10_DVAJCA_ISTOVREMENO_PROVERUVAAT, null, 0, null);
- private LimitedCounter fills = new LimitedCounter(0, 3, 7, _7_NEMA_MESTO_POKRAJ_KAZANOT, null, 0, null);
- private LimitedCounter eat = new LimitedCounter(0);
- public State() {
- }
- public boolean isPotEmpty() throws RuntimeException {
- log(checks.incrementWithMax(), "proverka dali ima hrana vo kazanot");
- sleep(5);
- boolean res = platesLeft.getValue() == 0;
- log(checks.decrementWithMin(), null);
- return res;
- }
- public void fillPlate() throws RuntimeException {
- log(fills.incrementWithMax(), "zemanje na hrana");
- log(platesLeft.decrementWithMin(), null);
- sleep(5);
- log(platesLeft.incrementWithMax(), null);
- log(fills.decrementWithMin(), null);
- }
- public void eat() throws RuntimeException {
- log(eat.incrementWithMax(), "jadenje");
- sleep(10);
- log(eat.decrementWithMin(), null);
- }
- public void cook() throws RuntimeException {
- synchronized (State.class) {
- if (platesLeft.getValue() == 0) {
- platesLeft.setValue(POT_CAPACITY);
- } else {
- PointsException e = new PointsException(5, _5_NE_MOZE_DA_SE_GOTVI_VO_KAZAN_KOJ_NE_E_PRAZEN);
- log(e, null);
- }
- }
- }
- public void finalize() {
- if (fills.getMax() == 1) {
- logException(new PointsException(10, _10_PRISTAPOT_DO_KAZANOT_NE_E_PARALELIZIRAN));
- }
- if (eat.getMax() == 1) {
- logException(new PointsException(10, _10_JADENJETO_NE_E_PARALELIZIRANO));
- }
- }
- private List<String> actions = new ArrayList<String>();
- private void sleep(int range) {
- try {
- Thread.sleep(RANDOM.nextInt(range));
- } catch (InterruptedException e) {
- }
- }
- protected TemplateThread getThread() {
- TemplateThread t = (TemplateThread) Thread.currentThread();
- return t;
- }
- private synchronized void log(PointsException e, String action) {
- TemplateThread t = (TemplateThread) Thread.currentThread();
- if (e != null) {
- t.setException(e);
- actions.add(t.toString() + "\t(e): " + e.getMessage());
- } else if (action != null) {
- actions.add(t.toString() + "\t(a): " + action);
- }
- }
- private synchronized void logException(PointsException e) {
- actions.add("\t(e): " + e.getMessage());
- }
- public synchronized void printLog() {
- System.out.println(
- "Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
- System.out.println("Log na izvrsuvanje na akciite:");
- System.out.println("=========================");
- System.out.println("tip\tid\titer\takcija/error");
- System.out.println("=========================");
- for (String l : actions) {
- System.out.println(l);
- }
- }
- public void printStatus() {
- finalize();
- if (!TemplateThread.hasException) {
- int poeni = 25;
- if (PointsException.getTotalPoints() == 0) {
- System.out.println("Procesot e uspesno sinhroniziran. Osvoeni 25 poeni.");
- } else {
- poeni -= PointsException.getTotalPoints();
- PointsException.printErrors();
- System.out.println("Maksimalni osvoeni poeni: " + poeni);
- }
- } else {
- System.out.println("Procesot ne e sinhroniziran spored uslovite na zadacata");
- printLog();
- System.out.println("====================================================");
- PointsException.printErrors();
- int total = (25 - PointsException.getTotalPoints());
- if (total < 0) {
- total = 0;
- }
- System.out.println("Maksimum Poeni: " + total);
- }
- }
- }
- static class LimitedCounter {
- private int value;
- private Integer maxAllowed;
- private Integer minAllowed;
- private int maxErrorPoints;
- private int minErrorPoints;
- private String maxErrorMessage;
- private String minErrorMessage;
- private int max;
- public LimitedCounter(int value) {
- super();
- this.value = value;
- this.max = value;
- }
- public LimitedCounter(int value, Integer maxAllowed, int maxErrorPoints, String maxErrorMessage,
- Integer minAllowed, int minErrorPoints, String minErrorMessage) {
- super();
- this.value = value;
- this.max = value;
- this.maxAllowed = maxAllowed;
- this.minAllowed = minAllowed;
- this.maxErrorPoints = maxErrorPoints;
- this.minErrorPoints = minErrorPoints;
- this.maxErrorMessage = maxErrorMessage;
- this.minErrorMessage = minErrorMessage;
- }
- public int getMax() {
- return max;
- }
- public int getValue() {
- return value;
- }
- public void setValue(int value) {
- this.value = value;
- }
- public PointsException incrementWithMax() {
- synchronized (LimitedCounter.class) {
- value++;
- if (value > max) {
- max = value;
- }
- if (maxAllowed != null) {
- if (value > maxAllowed) {
- PointsException e = new PointsException(maxErrorPoints, maxErrorMessage);
- return e;
- }
- }
- }
- return null;
- }
- public PointsException decrementWithMin() {
- synchronized (LimitedCounter.class) {
- value--;
- if (minAllowed != null) {
- if (value < minAllowed) {
- PointsException e = new PointsException(minErrorPoints, minErrorMessage);
- return e;
- }
- }
- }
- return null;
- }
- }
- abstract static class TemplateThread extends Thread {
- static boolean hasException = false;
- int numRuns = 1;
- public int iteration = 0;
- protected Exception exception = null;
- public TemplateThread(int numRuns) {
- this.numRuns = numRuns;
- }
- abstract void execute() throws InterruptedException;
- @Override
- public void run() {
- try {
- for (int i = 0; i < numRuns&&!hasException; i++) {
- execute();
- iteration++;
- }
- } catch (InterruptedException e) {
- // Do nothing
- } catch (Exception e) {
- exception = e;
- hasException = true;
- }
- }
- public void setException(Exception exception) {
- this.exception = exception;
- hasException = true;
- }
- @Override
- public String toString() {
- Thread current = Thread.currentThread();
- if (numRuns > 1) {
- return String.format("%s\t%d\t%d", "" + current.getClass().getSimpleName().charAt(0), getId(),
- iteration);
- } else {
- return String.format("%s\t%d\t", "" + current.getClass().getSimpleName().charAt(0), getId());
- }
- }
- }
- static class PointsException extends RuntimeException {
- private static HashMap<String, PointsException> exceptions = new HashMap<String, PointsException>();
- private int points;
- public PointsException(int points, String message) {
- super(message);
- this.points = points;
- exceptions.put(message, this);
- }
- public static int getTotalPoints() {
- int sum = 0;
- for (PointsException e : exceptions.values()) {
- sum += e.getPoints();
- }
- return sum;
- }
- public static void printErrors() {
- System.out.println("Gi imate slednite greski: ");
- for (Map.Entry<String, PointsException> e : exceptions.entrySet()) {
- System.out.println(String.format("[%s] : (-%d)", e.getKey(), e.getValue().getPoints()));
- }
- }
- public int getPoints() {
- return points;
- }
- }
- public static void main(String[] args) {
- try {
- start();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- public static void start() throws Exception {
- Scanner s = new Scanner(System.in);
- int brKonzumeri = s.nextInt();
- int numCustomerRuns = s.nextInt();
- init(brKonzumeri);
- state = new State();
- HashSet<Thread> threads = new HashSet<Thread>();
- for (int i = 0; i < brKonzumeri; i++) {
- TribeMember c = new TribeMember(numCustomerRuns);
- threads.add(c);
- c.start();
- }
- try {
- Thread.sleep(50);
- } catch (Exception e) {
- // do nothing
- }
- for (Thread t : threads) {
- t.join(1000);
- }
- for (Thread t : threads) {
- if (t.isAlive()) {
- t.interrupt();
- if (t instanceof TemplateThread) {
- TemplateThread tt = (TemplateThread) t;
- tt.setException(new PointsException(25, "DEADLOCK"));
- }
- }
- }
- s.close();
- state.printStatus();
- }
- // </editor-fold>
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement