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)
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With