javac
javac

Reputation: 461

How to share a variable among the threads?

I have two threads named t1 and t2. They only make an addition to total integer variable. But the variable total isn't shared among these threads. I want to use same total variable in both the t1 and t2 threads. How can I do that?

My Adder runnable class:

public class Adder implements Runnable{

    int a;
    int total;

    public Adder(int a) {
        this.a=a;
        total = 0;
    }

    public int getTotal() {
        return total;
    }

    @Override
    public void run() {
        total = total+a;

    }

}

My Main class:

public class Main {

    public static void main(String[] args) {

        Adder adder1=new Adder(2);

        Adder adder2= new Adder(7);

        Thread t1= new Thread(adder1);
        Thread t2= new Thread(adder2);

        thread1.start();
        try {
            thread1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t2.start();
        try {
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        System.out.println(adder1.getTotal());  //prints 7 (But it should print 9)
        System.out.println(adder2.getTotal()); //prints 2  (But it should print 9)


    }

}

Both print statements should give 9 but they give 7 and 2 respectively (because the total variable doesn't isn't by t1 and t2).

Upvotes: 1

Views: 108

Answers (1)

Mureinik
Mureinik

Reputation: 312126

The easy way out would be to make total static so it's shared between all Adder instances.

Note that such a simplistic approach would be sufficient for the main method you shared here (which doesn't really run anything in parallel, since each thread is joined right after being started). For a thread-safe solution, you'll need to protect the addition, e.g., by using an AtomicInteger:

public class Adder implements Runnable {

    int a;
    static AtomicInteger total = new AtomicInteger(0);

    public Adder(int a) {
        this.a = a;
    }

    public int getTotal() {
        return total.get();
    }

    @Override
    public void run() {
        // return value is ignored
        total.addAndGet(a);
    }
}

Upvotes: 3

Related Questions