繁体   English   中英

volatile关键字:需要对此程序行为进行解释

[英]volatile keyword : Need explanation for this program behaviour

通过此程序了解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变量的写入将立即写入主内存,并且应该立即对其他线程“可见”。 为什么在调用stopIt()之后t1线程仍然执行? 想知道现在的vol值是10而不是5吗?

没有证据表明在调用stopIt()之后t1正在运行。

事情可能以这种顺序发生

     t1                     t2
                         System.out.println("calling stopIt()");
while(vol==5)
System.out.println("Inside run")
                         enter stopIt()
                         vol = 10

这会给您观察到的结果。 (还有其他可能的订购结果,您可以得到此结果。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM