Java synchronized 關鍵字
示例
使用 synchronized
修飾符以防止執行緒之間的競態條件
public class Main implements Runnable {
public static int a, b;
public static void main(String[] args) {
a = 100;
b = 100;
// Check the total amount shared between a and b before the transfers
System.out.println("Total before: " + (a + b));
// Run threads which will transfer amounts between a and b
Thread thread1 = new Thread(new Main());
Thread thread2 = new Thread(new Main());
thread1.start();
thread2.start();
// Wait for the threads to finish running
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Check the total amount shared between a and b after the transfers
// It should be the same amount as before
System.out.println("Total after: " + (a + b));
}
public void run() {
for (int i = 0; i < 10000000; i++) {
transfer();
}
}
public static synchronized void transfer() {
// Choose a random amount to transfer
int amount = (int) (5.0 * Math.random());
// Transfer between a and b
if (a > b) {
a -= amount;
b += amount;
} else {
a += amount;
b -= amount;
}
}
}
定義和用法
synchronized
關鍵字是一個修飾符,用於鎖定一個方法,使其一次只能被一個執行緒使用。這可以防止執行緒之間競態條件引起的問題。
在上面的示例中,如果從 transfer()
方法中移除 synchronized
關鍵字,可能會導致 a
和 b
的值在操作之間被另一個執行緒修改。這將導致兩個變數的總量發生變化。
相關頁面
在我們的 Java 修飾符教程 中瞭解更多關於修飾符的資訊。
在我們的 Java 執行緒教程 中瞭解更多關於執行緒的資訊。