我有一个实现游戏的 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/