java - 对象的所有实例是否共享一个 volatile 变量?

标签 java multithreading volatile

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

负责游戏整体的类也实现了Runnable接口(interface),并重写了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?
  }
}

我想知道的是,如果变量是可变的,游戏类的每个实例是否会共享相同的 endThread 变量,以便当一个线程使用 stop() 停止时,所有其他线程也会停止?

最佳答案

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

您混淆的是 static 这里是 per-class 而不是 per-instance

有必读文章here

关于java - 对象的所有实例是否共享一个 volatile 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43051425/

相关文章:

java - PipedInputStream - 如何避免 "java.io.IOException: Pipe broken"

c++ - 我们可以用 `const_cast`来修饰一个常量吗?

c++ - 我们是否需要将 volatile 关键字和互斥锁一起用于线程安全?

java - SGE : Parallel Environment for a multithreaded java code

java - JButtons 大小不正确

java - 在 Java 中打印高度

c# - 如何获取另一个线程的 ThreadStatic 值?

c# - 在线程应用程序中准确计时一行代码,C#

java - JCIFS jcifs.smb.SmbException : A device attached to the system is not functioning

java - 关于java volatile 数组