Advertisement
tommyshelby

Untitled

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