Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. public class Solution {
  2. public static void main(String[] args) throws InterruptedException {
  3. Counter counter1 = new Counter();
  4. Counter counter2 = new Counter();
  5. Counter counter3 = new Counter();
  6. Counter counter4 = new Counter();
  7.  
  8. counter1.start();
  9. counter2.start();
  10. counter3.start();
  11. counter4.start();
  12.  
  13. counter1.join();
  14. counter2.join();
  15. counter3.join();
  16. counter4.join();
  17.  
  18.  
  19. for (int i = 1; i <= 100; i++) {
  20. if (values[i] != 1) {
  21. System.out.println("Массив values содержит элементы неравные 1");
  22. break;
  23. }
  24. }
  25. }
  26.  
  27. public static Integer count = 0;
  28. public static int[] values = new int[105];
  29.  
  30. static {
  31. for (int i = 0; i < 105; i++) {
  32. values[i] = 0;
  33. }
  34. }
  35.  
  36. public synchronized static void incrementCount() {
  37. count++;
  38. }
  39.  
  40. public synchronized static int getCount() {
  41. return count;
  42. }
  43.  
  44. public static class Counter extends Thread {
  45. @Override
  46. public void run() {
  47. do {
  48.  
  49. ---->>> synchronized (Counter.class) { <<<---
  50. incrementCount();
  51. values[getCount()]++;
  52. }
  53.  
  54. try {
  55. Thread.sleep(1);
  56. } catch (InterruptedException e) {
  57. }
  58. } while (getCount() < 100);
  59. }
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement