Change the value of the variable x in the main method using a thread

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

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

I want the student stream to change the value of maxScore, how do I do this in Java? (As in C, we can pass the maxScore address)

+3
source share
3 answers

You can not. You cannot change the value of a local variable from another thread.

However, you can use a mutable type with a field intand pass it to a new stream. For instance:

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

(Apache commons-lang provides a class MutableIntthat can be reused)

: public static. : , , synchronized AtomicInteger, .

+4

, . :

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

Adding Synchronized with methods was a solution for me, thanks

0
source

Source: https://habr.com/ru/post/1791741/


All Articles