提问人:laroy 提问时间:4/6/2017 更新时间:4/6/2017 访问量:227
影响 Java 中不同类中的变量
Affecting variables in different classes in Java
问:
例如,我有两个类,我正在尝试操作一个变量
public class A {
public static void main(String[] args) {
while(game_over[0] == false) {
System.out.println("in the while-loop");
}
System.out.println("out of the while-loop");
}
static boolean[] game_over = {false};
}
和
public class B {
public boolean[] game_over;
public printBoard(boolean[] game_over) {
this.game_over = game_over;
}
public void run() {
for (int i = 0; i < 10; i++) {
// do something
}
game_over[0] = true;
System.out.println("GAME OVER");
}
}
提供的代码片段并不意味着实际可行的代码,我更关心这个概念。在我的程序中,类 A 创建了一个利用类 B 的线程,我希望类 B 影响变量“game_over”,以便类 A 中的 while 循环将受到更改的影响......知道如何成功更新变量吗?谢谢。
答:
2赞
Erwin Bolwidt
4/6/2017
#1
不要为此使用数组,这样会更难确保应用程序没有数据竞争。
由于您希望能够将标志作为独立对象传递,因此实现正确的多线程应用程序的最简单方法是使用该类。game_over
AtomicBoolean
import java.util.concurrent.atomic.AtomicBoolean;
class B {
private AtomicBoolean game_over;
public B(AtomicBoolean game_over) {
this.game_over = game_over;
}
public void run() {
// do stuff
game_over.set(true);
}
}
在您的 A 类中:
public class A {
static AtomicBoolean game_over = new AtomicBoolean();
public static void main(String[] args) {
B b = new B();
Thread t = new Thread(b);
t.start();
while (!game_over.get()) {
System.out.println("in the while-loop");
}
System.out.println("out of the while-loop");
}
}
评论
0赞
Nir Alfasi
4/6/2017
好答案。另一种选择是将game_over声明为volatile
0赞
laroy
4/6/2017
我可以看到这是如何工作的,但是在A类中创建AtomicBoolean时遇到问题
0赞
Erwin Bolwidt
4/6/2017
@alfasin 只有当它不是数组时,这才有效。因为它是一个数组,所以 volatile 只影响对 game_over 数组引用的读取操作,而不会影响对数组第一个元素的后续写入操作 - 因此仍然不能保证类 A 中的主循环将看到更新。
0赞
Nir Alfasi
4/6/2017
没错,在我看来,我没有使用数组,而是使用一个简单的值:)))boolean
评论