Reputation: 4028
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)
Upvotes: 6
Views: 24958
Reputation: 13343
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]);
}
}
Upvotes: 1
Reputation: 69
adding Synchronized to the methods was a solution for me, thanks
Upvotes: 0
Reputation: 2499
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);
}
}
Upvotes: 9
Reputation: 597056
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 int
field, and pass it to the new thread. For example:
public class MutableInt {
private int value;
public void setValue(..) {..}
public int getValue() {..};
}
(Apache commons-lang provide a MutableInt
class which you can reuse)
Update: for a global variable you can simple use public static
fields. 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 synchronized
blocks, or AtomicInteger
, depending on the usages.
Upvotes: 8