-
Notifications
You must be signed in to change notification settings - Fork 327
/
Copy pathFinalInitialDemo.java
47 lines (38 loc) · 1.13 KB
/
FinalInitialDemo.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
package fucking.concurrency.demo;
/**
* @author hyy (hjlbupt at 163 dot com)
*/
public class FinalInitialDemo {
private int a;
private boolean flag;
private FinalInitialDemo demo;
public FinalInitialDemo() {
a = 1;
flag = true;
}
public void writer() {
demo = new FinalInitialDemo();
}
public void reader() {
if (flag) {
int i = a * a;
if (i == 0) {
// On my dev machine, the variable initial always success.
// To solve this problem, add final to the `a` field and `flag` field.
System.out.println("Fuck! instruction reordering occurred.");
}
}
}
@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
while (true) {
FinalInitialDemo demo = new FinalInitialDemo();
Thread threadA = new Thread(demo::writer);
Thread threadB = new Thread(demo::reader);
threadA.start();
threadB.start();
threadA.join();
threadB.join();
}
}
}