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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4981214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:56:00  来源:igfitidea点击:

Change value of a variable x in main method through running thread

javamultithreading

提问by John

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

Thread student = new Thread(client,????);
student.start();
}

I want student thread to change value of maxScore, how do I do it in Java? (Like in C we can pass the address of maxScore)

我想让学生线程改变 maxScore 的值,我如何在 Java 中做到这一点?(就像在 C 中我们可以传递 maxScore 的地址)

回答by Ilya Ivanov

You need a class object, if you want to modify value in separate thread. For example:

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

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

回答by Bozho

You can't. There is no way you can change the value of a local variable from another thread.

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

You can, however, use a mutable type that has an intfield, and pass it to the new thread. For example:

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

public class MutableInt {
    private int value;
    public void setValue(..) {..}
    public int getValue() {..};
}

(Apache commons-lang provide a MutableIntclass which you can reuse)

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

Update: for a global variable you can simple use public staticfields. Note that if you are willing not only to store some values in them, but also read them and do stuff depending on that, you would need to use synchronizedblocks, or AtomicInteger, depending on the usages.

更新:对于全局变量,您可以简单地使用public static字段。请注意,如果您不仅愿意在其中存储一些值,还愿意读取它们并根据这些值执行操作,则需要使用synchronized块或AtomicInteger,具体取决于用法。

回答by user3506473

adding Synchronized to the methods was a solution for me, thanks

添加同步到方法对我来说是一个解决方案,谢谢

回答by Andrii Omelchenko

Also, you can use array (of one element):

此外,您可以使用数组(一个元素):

public class Main {

    public static void main(String args[]) throws Exception {
        final int[] score = new int[1];
        score[0] = 1;

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

        Thread student = new Thread() {

            @Override
            public void run() {
                score[0]++;
            }
        };

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

        System.out.println("Result maxScore: " + score[0]);
    }
}