简体   繁体   English

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

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

understanding volatile keyword by this program: 通过此程序了解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();
 }
}

Output: 输出:

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

All writes to vol variable will be written to main memory immediately and should be "visible" to other threads immediately. 所有对vol变量的写入将立即写入主内存,并且应该立即对其他线程“可见”。 Why t1 thread still executes after stopIt() is called? 为什么在调用stopIt()之后t1线程仍然执行? Cant it see that vol value is now 10 and not 5? 想知道现在的vol值是10而不是5吗?

There is no evidence of t1 running after stopIt() is invoked. 没有证据表明在调用stopIt()之后t1正在运行。

It can be possible that things happen in this order 事情可能以这种顺序发生

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

which give you the result you observed. 这会给您观察到的结果。 (There are other possibilities of ordering that give you this result.) (还有其他可能的订购结果,您可以得到此结果。)

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

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