-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVolatileTest.java
48 lines (40 loc) · 1.46 KB
/
VolatileTest.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
37
38
39
40
41
42
43
44
45
46
47
48
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class VolatileTest extends Assert {
private int counter = 0;
private volatile int volatileCounter = 0;
private AtomicInteger atomicInteger = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
VolatileTest test = new VolatileTest();
while (true) {
test.testVolatile();
}
}
@Test
public void testVolatile() throws InterruptedException {
// Создаём много потоков
int numberOfThreads = 1000;
List<Thread> list = new ArrayList<>();
for (int i = 0; i < numberOfThreads; ++i) {
Thread t = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
counter++;
volatileCounter++;
atomicInteger.incrementAndGet();
}
});
t.start();
list.add(t); // Добавляем поток в список
}
for (Thread t : list)
t.join();
System.out.println("counter = " + counter);
System.out.println("volatileCounter = " + volatileCounter);
System.out.println("atomicInteger = " + atomicInteger);
assertTrue(counter < atomicInteger.get());
assertTrue(volatileCounter < atomicInteger.get());
}
}