Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package lygiagratusistest1;
- /**
- *
- * @author Linas
- */
- public class ManoTest1 {
- public static Monitorius monitorius = new Monitorius();
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- Thread[] procesai = new Thread[5];
- for (int i = 0; i < 5; i++) {
- if (i < 2) {
- procesai[i] = new Thread(new Writer(i + 1));
- } else {
- procesai[i] = new Thread(new Reader(i + 1));
- }
- }
- for (int i = 0; i < procesai.length; i++) {
- procesai[i].start();
- }
- }
- public static class Monitorius {
- volatile int c, d;
- int readCounter;
- int printCounter;
- public Monitorius() {
- c = 10;
- d = 100;
- readCounter = 0;
- printCounter = 0;
- }
- public synchronized void Write(int id) {
- try {
- while (readCounter < 2 && printCounter < 15) {
- wait();
- }
- } catch (InterruptedException e) {
- }
- if (printCounter < 15) {
- c = c + id;
- d = d - id;
- readCounter = 0;
- notifyAll();
- }
- }
- public synchronized int[] Read(int id, int c1, int d1) {
- try {
- while ((c == c1 && d == d1) && printCounter < 15) {
- wait();
- }
- } catch (InterruptedException e) {
- }
- if (printCounter < 15) {
- System.out.println((printCounter + 1) + ") g:" + id + " c: " + c + " d: " + d);
- readCounter++;
- printCounter++;
- int[] arr = {c, d};
- notifyAll();
- return arr;
- }
- return null;
- }
- }
- static class Writer implements Runnable {
- int id;
- Writer(int gijosNr) {
- this.id = gijosNr;
- }
- @Override
- public void run() {
- while (monitorius.printCounter < 15) {
- monitorius.Write(id);
- }
- }
- }
- static class Reader implements Runnable {
- int id;
- int c1, d1;
- Reader(int gijosNr) {
- id = gijosNr;
- c1 = -1;
- d1 = -1;
- }
- @Override
- public void run() {
- while (monitorius.printCounter < 15) {
- int[] arr = monitorius.Read(id, c1, d1);
- if (arr != null) {
- c1 = arr[0];
- d1 = arr[1];
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement