Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package lab.vtora;
- import java.util.HashSet;
- import java.util.Random;
- import java.util.Scanner;
- public class CountThree {
- public static int NUM_RUNS = 100;
- /**
- * Promenlivata koja treba da go sodrzi brojot na pojavuvanja na elementot 3
- */
- int count = 0;
- int syncCount = 0;
- /**
- * TODO: definirajte gi potrebnite elementi za sinhronizacija
- */
- public static final Object monitor = new Object();
- public void init() {
- }
- class Counter extends Thread {
- private int counter;
- public void count(int[] data) throws InterruptedException {
- // da se implementira
- for (int i=0; i < data.length; ++i) {
- if (data[i] == 3) {
- counter++;
- }
- }
- // synchronized (this) {
- // int value = count;
- // int newValue = value + counter;
- // Thread.sleep(10);
- // count = newValue;
- // }
- synchronized (CountThree.class) {
- int value = count;
- int newValue = value + counter;
- Thread.sleep(10);
- count = newValue;
- }
- synchronized (monitor) {
- int value = syncCount;
- int newValue = value + counter;
- Thread.sleep(10);
- syncCount = newValue;
- }
- }
- private int[] data;
- public Counter(int[] data) {
- this.data = data;
- this.counter = 0;
- }
- @Override
- public void run() {
- try {
- count(data);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) {
- try {
- CountThree environment = new CountThree();
- environment.start();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- public void start() throws Exception {
- init();
- HashSet<Thread> threads = new HashSet<Thread>();
- Scanner s = new Scanner(System.in);
- int total=s.nextInt();
- Random random = new Random();
- for (int i = 0; i < NUM_RUNS; i++) {
- int[] data = new int[total];
- for (int j = 0; j < total; j++) {
- data[j] = random.nextInt(100);
- }
- Counter c = new Counter(data);
- threads.add(c);
- }
- for (Thread t : threads) {
- t.start();
- }
- for (Thread t : threads) {
- t.join();
- }
- System.out.println(count);
- System.out.println(syncCount);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement