挥发物

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;
    }
}