影响 Java 中不同类中的变量

Affecting variables in different classes in Java

提问人:laroy 提问时间:4/6/2017 更新时间:4/6/2017 访问量:227

问:

例如,我有两个类,我正在尝试操作一个变量

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 循环将受到更改的影响......知道如何成功更新变量吗?谢谢。

Java 变量 作用域 按值传递

评论

0赞 Maurice Perry 4/6/2017
拥有外部变量有什么意义?为什么不定义一个方法 B.isGameOver()?
1赞 Erwin Bolwidt 4/6/2017
@MauricePerry 我不知道 laroy 的原因,但一般来说,可能有很多组件可以决定游戏结束,为了避免 A 必须检查每个可以做出这个决定的组件,提供一定程度的间接性实际上是一个好主意。
0赞 Maurice Perry 4/6/2017
@ErwinBolwidt 好吧,在这种情况下,向他们传递一个类 GameStatus 或 GameMonitor 的对象,而不是布尔值。

答:

2赞 Erwin Bolwidt 4/6/2017 #1

不要为此使用数组,这样会更难确保应用程序没有数据竞争。

由于您希望能够将标志作为独立对象传递,因此实现正确的多线程应用程序的最简单方法是使用该类。game_overAtomicBoolean

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