是对象的所有实例共享的volatile变量吗?

时间:2017-03-27 16:11:28

标签: java multithreading volatile

我有一个实现游戏的java应用程序。

负责游戏整体的类也实现Runnable接口,并覆盖run方法,实现玩游戏的过程。此run()方法包含一个循环,该循环将继续运行,直到private volatile boolean endThread设置为true。这将通过一个名为stop()的方法完成,其中endThread设置为true。

我希望能够从我的main方法中停止一个特定的线程,调用stop()来结束玩游戏的特定线程,结束线程。

public class Game implements Runnable{
  private volatile boolean endThread;

  public Game(){
    endThread = false;
  }

  public void run(){
    while(endThread != true){
      // insert code to simulate the process of running the game
    }
    System.out.println("Game ended. Ending thread.");
  }

  public void stop(){ 
    endThread = true;
  }
}

public class Main{
  public static void main(String[] args){
    Game gameOne = new Game();
    Thread threadOne = new Thread(gameOne);
    threadOne.start();
    Game gameTwo = new Game();
    Thread threadTwo = new Thread(gameTwo);
    threadTwo.start();
    threadTwo.stop(); // will this stop threadOne aswell?
  }
}

我想知道的是,如果变量是volatile,那么游戏类的每个实例都会共享相同的endThread变量,这样当一个线程使用stop()停止时,所有其他线程也会停止吗?

1 个答案:

答案 0 :(得分:3)

这里确实需要volatile修饰符,因为它引入了可见性。如果您在读取时删除了volatile 可能永远不会看到更新的值,那么volatile关键字将确保一旦写入,其他线程就可以看到它。

你感到困惑的是static这里是一个每个类而不是每个实例

必读文章here