Change value of a variable x in main method through running thread Change value of a variable x in main method through running thread multithreading multithreading

Change value of a variable x in main method through running thread


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


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.


adding Synchronized to the methods was a solution for me, thanks