forked from lihengming/java-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVolatileTest.java
More file actions
58 lines (51 loc) · 1.57 KB
/
Copy pathVolatileTest.java
File metadata and controls
58 lines (51 loc) · 1.57 KB
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
55
56
57
58
package volatiles;
/**
* Created by 李恒名 on 2017/6/14.
*/
public class VolatileTest {
private /*volatile*/ int sharedValue = 0;
public static void main(String[] args) throws InterruptedException {
VolatileTest test = new VolatileTest();
new Thread(() -> test.listener()).start();
new Thread(() -> test.increment()).start();
/**
输出:
Value Incrementing:1
Value Incrementing:2
Value Incrementing:3
Value Incrementing:4
Value Incrementing:5
使用 volatile 修饰 sharedValue后:
Value Incrementing:1
Value Changed:1
Value Incrementing:2
Value Changed:2
Value Incrementing:3
Value Changed:3
Value Incrementing:4
Value Changed:4
Value Incrementing:5
Value Changed:5
*/
}
public void listener() {
int localValue = sharedValue;
while (sharedValue < 5) {
if (localValue != sharedValue) {
System.out.println("Value Changed:" + sharedValue);
localValue = sharedValue;
}
}
}
public void increment() {
while (sharedValue < 5) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
++sharedValue;
System.out.println("Value Incrementing:" + sharedValue);
}
}
}