并发变成-Volatile
作者:互联网
一、以下代码会如何执行
public class test {
public static void main(String [] args){
ThreadDemo td = new ThreadDemo();
new Thread(td).start();
while(true){
if(td.isFlag()){
System.out.println("Thread end");
}
}
}
}
class ThreadDemo implements Runnable {
private boolean flag = false;
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = true;
System.out.println("ThreadDemo end");
}
public boolean isFlag(){
return this.flag;
}
}
结果为主线程死循环下去,因为子线程修改的字段未刷新到主存中,导致主线程对flag一直不可见,增加volatile后可即时获取到子线程的修改。
标签:Thread,ThreadDemo,并发,flag,td,Volatile,线程,变成,public 来源: https://blog.csdn.net/wangaz521/article/details/98965714