如何在线程之间共享变量?

时间:2019-12-29 12:05:17

标签: java multithreading java-threads

我有两个名为t1t2的线程。它们仅添加total整数变量。但是变量total没有在这些线程之间共享。我想在totalt1线程中使用相同的t2变量。我该怎么办?

我的Adder可运行类:

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;

    }

}

我的主班:

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)


    }

}

两个print语句应分别给出9,但它们分别给出7和2(因为总变量不是t1t2的值)。

1 个答案:

答案 0 :(得分:3)

最简单的方法是制作total static,使其在所有Adder实例之间共享。

请注意,对于您在此处共享的main方法而言,这样一种简单的方法就足够了(它实际上并没有并行运行任何东西,因为每个线程在启动后就join被执行了)。对于线程安全的解决方案,您需要保护附加内容,例如,使用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);
    }
}
相关问题