Created
November 9, 2017 16:46
-
-
Save shiehnpin/6cd47d52c87e530922d7ead5ff6ba1af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TestVolatile { | |
volatile private boolean v = true; | |
private boolean n = true; | |
void invokeLoop(final boolean isVolatile){ | |
Thread t = new Thread(){ | |
@Override | |
public void run(){ | |
while(true){ | |
if(isVolatile){ | |
if(v){ | |
System.out.println("volatile been changed."); | |
v = false; | |
} | |
}else{ | |
if(n){ | |
System.out.println("non-volatile been changed."); | |
n = false; | |
} | |
} | |
} | |
} | |
}; | |
t.start(); | |
while(true){ | |
if(isVolatile){ | |
if(!v){ | |
v = true; | |
System.out.println("change volatile"); | |
} | |
}else{ | |
if(!n){ | |
n = true; | |
System.out.println("change non-volatile"); | |
} | |
} | |
} | |
} | |
public static void main(String[] avg){ | |
new TestVolatile().invokeLoop(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
isVolatile -> 交替輸出
!isVolatile -> 輸出一陣子就沒了