簡體   English   中英

如何在線程之間共享變量?

[英]How to share a variable among the threads?

我有兩個名為t1t2線程。 他們只對total整數變量進行加法。 但是變量total不在這些線程之間共享。 我想在t1t2線程中使用相同的total變量。 我怎樣才能做到這一點?

我的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)


    }

}

兩個打印語句都應該給出 9 但它們分別給出 7 和 2(因為 total 變量不是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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM