Skip to content

Commit beb1f83

Browse files
committed
程序顺序规则
1 parent 4eb8b4f commit beb1f83

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

thread/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@
117117
## [volatile](src/main/java/com/cpucode/java/volati)
118118

119119
- [x] [volatile的可见性](src/main/java/com/cpucode/java/volati/VolatileDemo.java)
120+
- [x] [程序顺序规则](src/main/java/com/cpucode/java/volati/BeforeDemo.java)
120121

121122
- [返回文件目录](#文件目录)
122123

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.cpucode.java.volati;
2+
3+
/**
4+
* @author : cpucode
5+
* @date : 2021/7/28
6+
* @time : 10:38
7+
* @github : https://github.com/CPU-Code
8+
* @csdn : https://blog.csdn.net/qq_44226094
9+
*/
10+
public class BeforeDemo {
11+
static int a = 0;
12+
static volatile boolean flag = false;
13+
14+
public static void main(String[] args) throws InterruptedException {
15+
16+
Thread thread = new Thread(() -> {
17+
a = 1;
18+
flag = true;
19+
}, "writer");
20+
21+
Thread thread2 = new Thread(() -> {
22+
if (flag){
23+
int x = a;
24+
25+
System.out.println(x);
26+
}
27+
}, "reader");
28+
29+
thread.start();
30+
Thread.sleep(500);
31+
thread2.start();
32+
}
33+
}

0 commit comments

Comments
 (0)