Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1.  
  2. import java.util.HashSet;
  3. import java.util.Random;
  4. import java.util.Scanner;
  5. import java.util.concurrent.Semaphore;
  6.  
  7. public class CountThree {
  8.  
  9. public static int NUM_RUNS = 100;
  10. /**
  11. * Promenlivata koja treba da go sodrzi brojot na pojavuvanja na elementot 3
  12. */
  13. int count = 0;
  14. /**
  15. * TODO: definirajte gi potrebnite elementi za sinhronizacija
  16. */
  17.  
  18. Semaphore mutex;
  19.  
  20. public void init() {
  21. mutex= new Semaphore(1);
  22. }
  23.  
  24.  
  25. class Counter extends Thread {
  26.  
  27. public void count(int[] data) throws InterruptedException {
  28. for(int i =0;i<data.length;i++)
  29. {
  30. if(data[i]==3)
  31. {
  32. mutex.acquire();
  33. ++count;
  34. mutex.release();
  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. CountThree environment = new CountThree();
  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. Random random= new Random();
  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] = random.nextInt(100);
  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