How can I use the volatile keyword in Java correctly?

前端 未结 6 1977
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 14:31

Say I have two threads and an object. One thread assigns the object:

public void assign(MyObject o) {
    myObject = o;
}

Another thread uses t

6条回答
  •  伪装坚强ぢ
    2021-02-05 15:27

    Declaring a volatile Java variable means:

    • The value of this variable will never be cached thread-locally
    • Access to the variable acts as though it is enclosed in a synchronized block

    The typical and most common use of volatile is :

    public class StoppableThread extends Thread {
      private volatile boolean stop = false;
    
      public void run() {
        while (!stop) {
          // do work 
        }
      }
    
      public void stopWork() {
        stop = true;
      }
    }
    

提交回复
热议问题