溫馨提示×

java多線程怎么對公共變量賦值

小億
141
2023-10-24 22:47:17
欄目: 編程語言

在Java多線程中,可以使用synchronized關(guān)鍵字來實現(xiàn)對公共變量的賦值。

首先,需要定義一個共享的變量,多個線程都可以修改該變量的值。例如:

public class SharedVariable {
    private int value;

    public synchronized void setValue(int newValue) {
        this.value = newValue;
    }

    public synchronized int getValue() {
        return value;
    }
}

在上述代碼中,使用synchronized關(guān)鍵字修飾了setValue和getValue方法,確保了在多線程環(huán)境下對value變量的讀寫操作是原子性的。

然后,可以創(chuàng)建多個線程來修改共享變量的值。例如:

public class Main {
    public static void main(String[] args) {
        SharedVariable sharedVariable = new SharedVariable();

        Thread thread1 = new Thread(() -> {
            sharedVariable.setValue(10);
        });

        Thread thread2 = new Thread(() -> {
            sharedVariable.setValue(20);
        });

        thread1.start();
        thread2.start();

        // 等待線程執(zhí)行完成
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        int value = sharedVariable.getValue();
        System.out.println("value: " + value);
    }
}

在上述代碼中,創(chuàng)建了兩個線程thread1和thread2來修改共享變量sharedVariable的值。使用join方法等待線程執(zhí)行完成后,再打印共享變量的值。

需要注意的是,使用synchronized關(guān)鍵字會帶來性能的損耗,因此在實際應(yīng)用中,可以根據(jù)具體的需求選擇其他的線程同步機制,如使用Lock對象、使用volatile關(guān)鍵字等。

0