共計 932 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 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 方法,確保了在多線程環(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 關鍵字會帶來性能的損耗,因此在實際應用中,可以根據具體的需求選擇其他的線程同步機制,如使用 Lock 對象、使用 volatile 關鍵字等。
丸趣 TV 網 – 提供最優(yōu)質的資源集合!
正文完
發(fā)表至: Java
2023-12-16