John
John

Reputation: 4028

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)

Upvotes: 6

Views: 24958

Answers (4)

Andrii Omelchenko
Andrii Omelchenko

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

user3506473
user3506473

Reputation: 69

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

Upvotes: 0

Ilya Ivanov
Ilya Ivanov

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

Bozho
Bozho

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

Related Questions