mirror of
https://github.com/Snailclimb/JavaGuide
synced 2025-06-25 02:27:10 +08:00
Update unsafe.md
This commit is contained in:
parent
752fc401cb
commit
7c88811e3e
@ -258,21 +258,19 @@ class ChangeThread implements Runnable{
|
|||||||
在主线程的`while`循环中,加入内存屏障,测试是否能够感知到`flag`的修改变化:
|
在主线程的`while`循环中,加入内存屏障,测试是否能够感知到`flag`的修改变化:
|
||||||
|
|
||||||
```java
|
```java
|
||||||
@Getter
|
public static void main(String[] args){
|
||||||
class ChangeThread implements Runnable{
|
ChangeThread changeThread = new ChangeThread();
|
||||||
/**volatile**/ boolean flag=false;
|
new Thread(changeThread).start();
|
||||||
@Override
|
while (true) {
|
||||||
public void run() {
|
boolean flag = changeThread.isFlag();
|
||||||
try {
|
unsafe.loadFence(); //加入读内存屏障
|
||||||
Thread.sleep(3000);
|
if (flag){
|
||||||
} catch (InterruptedException e) {
|
System.out.println("detected flag changed");
|
||||||
e.printStackTrace();
|
break;
|
||||||
}
|
}
|
||||||
System.out.println("subThread change flag to:" + flag);
|
|
||||||
flag = true;
|
|
||||||
}
|
}
|
||||||
|
System.out.println("main thread end");
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
运行结果:
|
运行结果:
|
||||||
|
Loading…
x
Reference in New Issue
Block a user