簡體   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