在Java中,避免競態條件的方法之一是使用synchronized
關鍵字來確保多個線程不會同時訪問共享資源。例如:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
在這個例子中,increment()
和getCount()
方法都被聲明為synchronized
,這意味著在同一時間只能有一個線程執行這兩個方法中的任何一個。這樣可以確保count
變量的一致性,從而避免競態條件。