-
Notifications
You must be signed in to change notification settings - Fork 1
/
Volatile.java
54 lines (46 loc) · 1.2 KB
/
Volatile.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
49
50
51
52
53
54
package vol;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* Демонстрация volatile
*/
public class Volatile extends Assert {
/**
* a
*/
@Test
public void testVolatile() throws InterruptedException {
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
Thread t1 = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
TestVolatile.one();
TestVolatile.two();
}
});
threads.add(t1);
t1.start();
}
// Ждём завершения всех потоков
for (Thread t : threads)
t.join();
assertTrue(TestVolatile.diffCounter > 0);
}
static class TestVolatile {
static volatile int i = 0, j = 0;
static int diffCounter = 0;
static void one() {
i++;
j++;
}
static void two() {
int lj = j, li = i;
if (lj != li) {
diffCounter++;
//System.out.println("i=" + li + " j=" + lj);
}
}
}
}