Advertisement
Guest User

vtora cetvrta

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