通过该程序了解volatile关键字:
public class VolatileExample implements Runnable{
private volatile int vol;
@Override
public void run(){
vol=5;
while(vol==5)
{
System.out.println("Inside run when vol is 5. Thread is : "+Thread.currentThread().getName());
if("t2".equals(Thread.currentThread().getName()))
{
System.out.println("Got Thread : "+Thread.currentThread().getName()+" Now Calling Stop To End This Flow");
stopIt();
}
}
}
public void stopIt(){
vol=10;
}
public static void main(String[] args){
VolatileExample ve1 = new VolatileExample();
VolatileExample ve2 = new VolatileExample();
Thread t1 = new Thread(ve1);
Thread t2 = new Thread(ve1); //t1 and t2 operate on same instance of VolatileExample class
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
输出:
Inside run when vol is 5. Thread is : t1
Inside run when vol is 5. Thread is : t1
Inside run when vol is 5. Thread is : t2
Inside run when vol is 5. Thread is : t1
Got Thread : t2 Now Calling Stop To End This Flow
Inside run when vol is 5. Thread is : t1
对vol变量的所有写操作都将立即写入主存,并且应立即对其他线程“可见”。 为什么t1线程在调用stopIt()后仍然执行?不能看到卷值现在是10而不是5?
答案 0 :(得分:3)
在调用t1
之后,没有stopIt()
运行的证据。
事情有可能按此顺序发生
t1 t2
System.out.println("calling stopIt()");
while(vol==5)
System.out.println("Inside run")
enter stopIt()
vol = 10
它可以为您提供观察到的结果。 (订购的其他可能性可以为您提供此结果。)