影响Java中不同类中的变量
举个例子,我有两个类,我正试图用它们来操作一个变量影响Java中不同类中的变量,java,variables,scope,pass-by-value,Java,Variables,Scope,Pass By Value,举个例子,我有两个类,我正试图用它们来操作一个变量 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"); }
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};
}
及
公共B类{
公共布尔[]游戏结束;
公共印刷板(布尔[]游戏结束){
this.game\u over=game\u over;
}
公开募捐{
对于(int i=0;i<10;i++){
//做点什么
}
game_over[0]=真;
System.out.println(“游戏结束”);
}
}
提供的代码片段并不意味着是实际可行的代码,我更关心的是这个概念。在我的程序中,类A创建了一个利用类B的线程,我希望类B影响变量“game_over”,这样类A中的while循环将受到更改的影响。。。知道如何成功更新变量吗?谢谢。不要为此使用阵列,这会使确保无数据竞争的应用程序更加困难 由于您希望能够将
game\u 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");
}
}
回答得好。另一个选择是将game_over声明为volatile,我可以看到这是如何工作的,但是我在类中创建AtomicBoolean时遇到了问题A@alfasin只有当它不是一个数组时,它才会起作用。因为它是一个数组,volatile只影响game_over array引用上的读取操作,而不影响以后对数组第一个元素的写入操作-因此仍然不能保证类A中的主循环会看到更新。是的,在我看来,我使用的不是数组,而是一个简单的
boolean
value:))拥有一个外部变量有什么意义?为什么不定义一个方法B.isGameOver()?@MauricePerry我不知道laroy的原因,但一般来说,可能有很多组件可以决定游戏是否结束,为了避免必须检查每个可能做出此决定的组件,提供一定程度的间接性实际上是一个好主意。@ErwinBolwidt好的,在这种情况下,向他们传递GameStatus或GameMonitor类的对象,而不是布尔值。
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");
}
}