Почему валидатор принимает синхронизацию по (Solution.class), но не принимает по (Counter.class)?Разве это не одно и тоже? Если будет захвачет мьютекс Counter.classб то нити точно также будут синхронизированны.
public class Solution {
public static void main(String[] args) throws InterruptedException {
Counter counter1 = new Counter();
Counter counter2 = new Counter();
Counter counter3 = new Counter();
Counter counter4 = new Counter();
counter1.start();
counter2.start();
counter3.start();
counter4.start();
counter1.join();
counter2.join();
counter3.join();
counter4.join();
for (int i = 1; i <= 100; i++) {
if (values[i] != 1) {
System.out.println("Массив values содержит элементы неравные 1");
break;
}
}
for(int i:values)
System.out.println(i);
}
public static volatile Integer count = 0;
public static int[] values = new int[105];
static {
for (int i = 0; i < 105; i++) {
values[i] = 0;
}
}
public static void incrementCount() {
count++;
}
public static int getCount() {
return count;
}
public static class Counter extends Thread {
@Override
public void run() {
do {
synchronized (Counter.class) { // ЗДЕСЬ ВАЛИДАТОР ПРИНИМАЕТ (Solution.class)
values[getCount()]++;
incrementCount();
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
} while (getCount() < 100);
}
}
}
Alexander Gromov
19 уровень
Вопрос по синхронизации
Обсуждается
Комментарии (4)
- популярные
- новые
- старые
Для того, чтобы оставить комментарий Вы должны авторизоваться
hidden #2322530
28 мая 2021, 07:47
Потому что классы Counter являются Nested, (статическими), а синхронизация для статических членов класса надо делать по классу, который их содержит. то есть Solution.
+6
Alexander Gromov
29 мая 2021, 15:42
Спасибо! Не подскажите откуда это узнали? Возможно в книгах эти вопросы подробнее рассматриваются?
0
hidden #2322530
29 мая 2021, 19:10
Гугл
0
Alexander Gromov
27 мая 2021, 18:25
Кто-нибудь?
0