-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSyncThread5.java
36 lines (33 loc) · 1.14 KB
/
SyncThread5.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.concurrent.atomic.AtomicInteger;
/**
* Синхронизация потоков
*/
public class SyncThread5 {
private static AtomicInteger x = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
while (true) {
final int X = 10000000;
x.set(0);
Thread incVar = new Thread(() -> {
for (int i = 0; i < X; i++) {
x.incrementAndGet();
// 1. Загрузить из памяти
// 2. Поменять значение
// 3. Записать в память
}
});
incVar.start();
Thread decVar = new Thread(() -> {
for (int i = 0; i < X; i++) {
x.decrementAndGet();
}
});
decVar.start();
// Подождём оба потока
incVar.join();
decVar.join();
// Какое же значение переменной?
System.out.println("x = " + x.get());
}
}
}