对象的所有实例是否共享一个 volatile 变量?
Is a volatile variable shared by all instances of an object?
我有一个 java 实现游戏的应用程序。
负责游戏整体的class也实现了Runnable接口,并重写了运行方法,实现了玩游戏的过程。此 运行() 方法包含一个循环,该循环将继续 运行 直到 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?
}
}
我想知道的是,如果变量是可变的,游戏的每个实例 class 是否会共享同一个 endThread 变量,这样当一个线程使用 stop() 停止时,所有其他线程也会停止?
这里确实需要 volatile 修饰符,因为它引入了可见性。如果删除 volatile
,您 可能永远不会在读取时看到更新的值 ,volatile 关键字将确保一旦写入,其他线程就可以看到它。
你混淆的是 static
这里是 per-class 而不是 per-instance.
有必读文章here
我有一个 java 实现游戏的应用程序。
负责游戏整体的class也实现了Runnable接口,并重写了运行方法,实现了玩游戏的过程。此 运行() 方法包含一个循环,该循环将继续 运行 直到 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?
}
}
我想知道的是,如果变量是可变的,游戏的每个实例 class 是否会共享同一个 endThread 变量,这样当一个线程使用 stop() 停止时,所有其他线程也会停止?
这里确实需要 volatile 修饰符,因为它引入了可见性。如果删除 volatile
,您 可能永远不会在读取时看到更新的值 ,volatile 关键字将确保一旦写入,其他线程就可以看到它。
你混淆的是 static
这里是 per-class 而不是 per-instance.
有必读文章here