Skip to content

Instantly share code, notes, and snippets.

@shiehnpin
Created November 9, 2017 16:46
Show Gist options
  • Save shiehnpin/6cd47d52c87e530922d7ead5ff6ba1af to your computer and use it in GitHub Desktop.
Save shiehnpin/6cd47d52c87e530922d7ead5ff6ba1af to your computer and use it in GitHub Desktop.
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);
}
}
@shiehnpin
Copy link
Author

isVolatile -> 交替輸出
!isVolatile -> 輸出一陣子就沒了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment