-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestVolatile.java
More file actions
executable file
·61 lines (54 loc) · 1.25 KB
/
TestVolatile.java
File metadata and controls
executable file
·61 lines (54 loc) · 1.25 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
59
60
61
package basic.thread;
/**
* �����ڴ�����
*
* �������volatile,success�ı��,��û��д��������ȥ,���Ǵ���CPU�Ļ����� ��Ȼ������synchronizedҲ����
*
* @author yangqc
*
*/
public class TestVolatile {
private boolean success = false;
public void getResult() {
while (true) {
try {
Thread.sleep(500);
Thread.yield();
} catch (InterruptedException e) {
System.out.println("sorry!");
}
if (success) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
public void setSuccess() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.success = true;
System.out.println("hello================");
}
public static void main(String[] args) throws InterruptedException {
final TestVolatile testVolatile = new TestVolatile();
Runnable task1 = new Runnable() {
@Override
public void run() {
testVolatile.setSuccess();
}
};
Runnable task2 = new Runnable() {
@Override
public void run() {
testVolatile.getResult();
}
};
new Thread(task2).start();
new Thread(task1).start();
System.out.println("==");
}
}