Advertisement
Azure47

OS Lab 2.2

Mar 24th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.03 KB | None | 0 0
  1. import java.util.HashSet;
  2. import java.util.Random;
  3. import java.util.Scanner;
  4. import java.util.concurrent.Semaphore;
  5.  
  6. public class CountThree {
  7.  
  8.     public static int NUM_RUNS = 100;
  9.     /**
  10.      * Promenlivata koja treba da go sodrzi brojot na pojavuvanja na elementot 3
  11.      */
  12.     int count = 0;
  13.     /**
  14.      * TODO: definirajte gi potrebnite elementi za sinhronizacija
  15.      */
  16.  
  17.     Semaphore s;
  18.  
  19.     public void init() {
  20.         s = new Semaphore(1);
  21.     }
  22.  
  23.     class Counter extends Thread {
  24.  
  25.         public void count(int[] data) throws InterruptedException {
  26.             // da se implementira
  27.  
  28.             for(int i=0;i<data.length;i++){
  29.                 if(data[i]==3){
  30.                     s.acquire();
  31.                     count++;
  32.                     s.release();
  33.                 }
  34.             }
  35.         }
  36.         private int[] data;
  37.  
  38.         public Counter(int[] data) {
  39.             this.data = data;
  40.         }
  41.  
  42.         @Override
  43.         public void run() {
  44.             try {
  45.                 count(data);
  46.             } catch (Exception e) {
  47.                 e.printStackTrace();
  48.             }
  49.         }
  50.     }
  51.  
  52.     public static void main(String[] args) {
  53.         try {
  54.             CountThree environment = new CountThree();
  55.             environment.start();
  56.         } catch (Exception ex) {
  57.             ex.printStackTrace();
  58.         }
  59.     }
  60.  
  61.     public void start() throws Exception {
  62.  
  63.         init();
  64.  
  65.         HashSet<Thread> threads = new HashSet<Thread>();
  66.         Scanner s = new Scanner(System.in);
  67.         int total=s.nextInt();
  68.  
  69.         for (int i = 0; i < NUM_RUNS; i++) {
  70.             int[] data = new int[total];
  71.             for (int j = 0; j < total; j++) {
  72.                 data[j] = s.nextInt();
  73.             }
  74.             Counter c = new Counter(data);
  75.             threads.add(c);
  76.         }
  77.  
  78.         for (Thread t : threads) {
  79.             t.start();
  80.         }
  81.  
  82.         for (Thread t : threads) {
  83.             t.join();
  84.         }
  85.         System.out.println(count);
  86.  
  87.  
  88.     }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement