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

标签 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并非总变量不是)。

最佳答案

最简单的方法是将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);
    }
}

关于java - 如何在线程之间共享变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59519239/

相关文章:

c++ - 如何使用 "priority"进行多线程处理?

c++ - 多线程 MongoDB C++ 客户端应用程序 : multiple DBClientConnections vs. 单个互斥锁?

java - WAIT 和 BLOCKED 线程状态之间的区别

java - 将 webelement 转换为字符串 Selenium

c# - Windows Phone map 不断崩溃

java - Java 类中的多个构造函数

如果实例化 Selenium WebDriver,Java 线程将失败

java - 情境使用 : Run tasks in ForkJoinPool vs. new Thread

Java:在单元测试中模拟 http/https 调用

java - 从java中的sql时间中删除秒