Advertisement
jaVer404

level17.lesson10.home10

Oct 15th, 2015
386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1. package com.javarush.test.level17.lesson10.home10;
  2.  
  3. /* Посчитаем
  4. 1. Сделай так, чтобы результат успел посчитаться для всех элементов массива values НЕ используя Thread.sleep
  5. 2. Исправь synchronized блок так, чтобы массив values заполнился значением 1
  6. */
  7.  
  8. public class Solution {
  9.     public static void main(String[] args) throws InterruptedException {
  10.         Counter counter1 = new Counter();
  11.         Counter counter2 = new Counter();
  12.         Counter counter3 = new Counter();
  13.         Counter counter4 = new Counter();
  14.  
  15.         counter1.start();
  16.         counter1.join();
  17.         counter2.start();
  18.         counter2.join();
  19.         counter3.start();
  20.         counter3.join();
  21.         counter4.start();
  22.         counter4.join();
  23.  
  24.  
  25.         for (int i = 1; i <= 100; i++) {
  26.             if (values[i] != 1) {
  27.                 System.out.println("Массив values содержит элементы неравные 1");
  28.                 break;
  29.             }
  30.         }
  31.         for (int i = 0; i< values.length; i++) {
  32.             System.out.println(values[i]);
  33.         }
  34.  
  35.     }
  36.  
  37.     public static Integer count = 0;
  38.     public static int[] values = new int[105];
  39.  
  40.     static {
  41.         for (int i = 0; i < 105; i++) {
  42.             values[i] = 0;
  43.         }
  44.     }
  45.  
  46.     public static void incrementCount() {
  47.         count++;
  48.     }
  49.  
  50.     public static int getCount() {
  51.         return count;
  52.     }
  53.  
  54.     public static class Counter extends Thread {
  55.         @Override
  56.         public void run() {
  57.             do {
  58.                 synchronized (Counter.class) {
  59.                     incrementCount();
  60.                     values[getCount()]++;
  61.                 }
  62.  
  63.                 try {
  64.                     Thread.sleep(1);
  65.                 } catch (InterruptedException e) {
  66.                 }
  67.             } while (getCount() < 100);
  68.         }
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement