【发布时间】:2017-03-27 16:11:27
【问题描述】:
我有一个实现游戏的 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() 停止一个线程时,所有其他线程也会停止?
【问题讨论】:
-
no - volatile 仅表示从标记为
volatile的变量中写入和读取是原子的,而不是更少,而不是更多 -
“... volatile 修饰符保证任何读取字段的线程都会看到最近写入的值。” - 乔什布洛赫。所以,没有不共享。
-
@bag 您将可见性(易失性给出)与共享性(静态给出)混淆了。如果你想让所有线程都看到变量的最新值,它需要是 volatile 的。
-
@AndyTurner 通过“所有线程看到变量的最新值”,你的意思是每个线程都会看到真正的最新值,如从 main 方法设置,该特定线程游戏类中的变量?还是说所有线程都能看到同一个变量的值?
-
@bag 每个线程都有它的 own 实例(它没有 static 修饰符)。所以当你调用
stop时,只有那个特定的线程会看到值是true。
标签: java multithreading volatile