Crazy

Threads - Задача 4

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