What is the volatile keyword useful for?

前端 未结 23 2666
闹比i
闹比i 2020-11-21 05:32

At work today, I came across the volatile keyword in Java. Not being very familiar with it, I found this explanation.

Given the detail in which that arti

23条回答
  •  旧巷少年郎
    2020-11-21 05:52

    volatile is very useful to stop threads.

    Not that you should be writing your own threads, Java 1.6 has a lot of nice thread pools. But if you are sure you need a thread, you'll need to know how to stop it.

    The pattern I use for threads is:

    public class Foo extends Thread {
    
      private volatile boolean close = false;
    
      public void run() {
        while(!close) {
          // do work
        }
      }
      public void close() {
        close = true;
        // interrupt here if needed
      }
    }
    

    In the above code segment, the thread reading close in the while loop is different from the one that calls close(). Without volatile, the thread running the loop may never see the change to close.

    Notice how there's no need for synchronization

提交回复
热议问题