溫馨提示×

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

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

在Java多線程中,可以使用synchronized關鍵字來實現對公共變量的賦值。

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

public class SharedVariable {
    private int value;

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

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

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

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

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();

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

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

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

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

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女