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

标签 java multithreading

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

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

我希望学生线程更改 maxScore 的值,我该如何在 Java 中执行此操作? (就像在 C 中我们可以传递 maxScore 的地址)

最佳答案

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

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

关于java - 通过运行线程更改 main 方法中变量 x 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4981214/

相关文章:

Python 线程返回值

java - 按集合中的内部集合元素类型分组

java - Android 通过标签获取图片源

java - JAXB 解码时出错

c++ - Xcode 中 C++ 中 Boost 线程的链接器错误

c++ - C++ 11 中的锁是否保证访问数据的新鲜度?

java - 为什么启动我的线程不调用 run() 方法?

java - 根据两个列表的差异创建指令列表

java - 需求标识符是什么意思?

java - 使用@Async调用方法与在新线程中调用方法