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{
258258在主线程的` while ` 循环中,加入内存屏障,测试是否能够感知到` flag ` 的修改变化:
259259
260260``` 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 ;
270270 }
271- System . out. println(" subThread change flag to:" + flag);
272- flag = true ;
273271 }
272+ System . out. println(" main thread end" );
274273}
275-
276274```
277275
278276运行结果:
You can’t perform that action at this time.
0 commit comments