Advertisement
Guest User

Untitled

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