Java 中不同 类 中的影响变量

Affecting variables in different classes in Java

我有两个 class 试图操纵一个变量,例如

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");
    }
}

提供的代码片段并不是实际可行的代码,我更关心的是概念。在我的程序中,class A 创建了一个利用 class B 的线程,我希望 class B 影响变量 'game_over',以便 [=21] 中的 while 循环=] A 将受到更改的影响...知道如何成功更新变量吗?谢谢

不要为此使用数组,这会使确保无数据争用应用程序变得更加困难。

由于您希望能够将 game_over 标志作为独立对象传递,实现正确的多线程应用程序的最简单方法是使用 AtomicBoolean class.

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);
    }
}

在你的 class 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");
    }
}