Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 425
John Avatar asked Feb 12 '11 23:02

John


1 Answers

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);
    }
}
like image 167
Ilya Ivanov Avatar answered Sep 18 '22 22:09

Ilya Ivanov