File tree Expand file tree Collapse file tree 1 file changed +10
-12
lines changed Expand file tree Collapse file tree 1 file changed +10
-12
lines changed Original file line number Diff line number Diff line change @@ -258,21 +258,19 @@ class ChangeThread implements Runnable{
258
258
在主线程的` while ` 循环中,加入内存屏障,测试是否能够感知到` flag ` 的修改变化:
259
259
260
260
``` java
261
- @Getter
262
- class ChangeThread implements Runnable {
263
- /* *volatile* */ boolean flag = false ;
264
- @Override
265
- public void run () {
266
- try {
267
- Thread . sleep( 3000 );
268
- } catch ( InterruptedException e) {
269
- e . printStackTrace() ;
261
+ public static void main( String [] args){
262
+ ChangeThread changeThread = new ChangeThread ();
263
+ new Thread (changeThread) . start() ;
264
+ while ( true ) {
265
+ boolean flag = changeThread . isFlag();
266
+ unsafe . loadFence(); // 加入读内存屏障
267
+ if (flag){
268
+ System . out . println( " detected flag changed " );
269
+ break ;
270
270
}
271
- System . out. println(" subThread change flag to:" + flag);
272
- flag = true ;
273
271
}
272
+ System . out. println(" main thread end" );
274
273
}
275
-
276
274
```
277
275
278
276
运行结果:
You can’t perform that action at this time.
0 commit comments