简体   繁体   中英

volatile keyword : Need explanation for this program behaviour

understanding volatile keyword by this program:

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. Why t1 thread still executes after stopIt() is called? Cant it see that vol value is now 10 and not 5?

There is no evidence of t1 running after stopIt() is invoked.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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