通过运行线程在main方法中更改变量x的值

Joh*_*ohn 4 java multithreading

public static void main(String args[]) throws Exception {
    int maxScore = 0;

Thread student = new Thread(client,????);
student.start();
}
Run Code Online (Sandbox Code Playgroud)

我希望学生线程改变maxScore的值,我该如何用Java做?(就像在C中我们可以传递maxScore的地址)

Ily*_*nov 8

如果要在单独的线程中修改值,则需要一个类对象.例如:

public class Main {

    private static class Score {
        public int maxScore;
    }

    public static void main(String args[]) throws Exception {
        final Score score = new Score();
        score.maxScore = 1;

        System.out.println("Initial maxScore: " + score.maxScore);

        Thread student = new Thread() {

            @Override
            public void run() {
                score.maxScore++;
            }
        };

        student.start();
        student.join(); // waiting for thread to finish

        System.out.println("Result maxScore: " + score.maxScore);
    }
}
Run Code Online (Sandbox Code Playgroud)


Boz*_*zho 5

你不能.您无法从另一个线程更改局部变量的值.

但是,您可以使用具有int字段的可变类型,并将其传递给新线程.例如:

public class MutableInt {
    private int value;
    public void setValue(..) {..}
    public int getValue() {..};
}
Run Code Online (Sandbox Code Playgroud)

(Apache commons-lang提供了一个MutableInt可以重用的类)

更新:对于全局变量,您可以简单地使用public static字段.请注意,如果您不仅愿意在其中存储某些值,而且还要阅读它们并根据具体情况执行操作,则需要使用synchronized块,或者AtomicInteger根据使用情况而定.