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/