揮發物

volatile 修飾符用於多執行緒程式設計。如果你將欄位宣告為 volatile,那麼它是執行緒的訊號,它們必須讀取最新值,而不是本地快取的值。此外,volatile 讀寫保證是原子的(訪問非 volatile longdouble 不是原子的),從而避免了多個執行緒之間的某些讀/寫錯誤。

public class MyRunnable implements Runnable
{
    private volatile boolean active;
 
    public void run(){ // run is called in one thread 
        active = true;
        while (active){
            // some code here
        }
    }
    
    public void stop(){ // stop() is called from another thread
        active = false;
    }
}