通过此程序了解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吗?

最佳答案

没有证据表明调用t1stopIt()运行。

事情可能以这种顺序发生

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


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

关于java - volatile关键字:需要对此程序行为进行解释,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43732734/

10-10 19:31