錯誤代碼同步塊如何工作?
public class Scheduler {
private Object lock = new Object();
private int interval;
private int period;
public Scheduler(int interval , int period) {
this.interval = interval;
this.period = period;
}
public synchronized void setInterval(int interval) {
this.interval = interval;
}
public synchronized void setPeriod(int period) {
this.period = period;
}
public void updateScheduler(int interval , int period) {
synchronized(lock) {
setPeriod(period);
setInterval(interval);
}
}
}
我有一些線程問題,在我的代碼找到那些,我在我的項目跑線程安全的Eclipse插件。
線程安全報告
- 在調度程序類
錯誤描述
爲了避免dataraces的
混合同步,重要的是,那些同時訪問域始終得到守衛一個共同的鎖。如果每次訪問一個字段時都沒有保持相同的鎖對象,則可能會發生datarace。
固定碼
public class Scheduler {
private Object lock = new Object();
private int interval;
private int period;
public Scheduler(int interval , int period) {
this.interval = interval;
this.period = period;
}
public void setInterval(int interval) {
synchronized(lock) {
this.interval = interval;
}
}
public void setPeriod(int period) {
synchronized(lock) {
this.period = period;
}
}
public void updateScheduler(int interval , int period) {
synchronized(lock) {
setPeriod(period);
setInterval(interval);
}
}
}
我測試此代碼,它工作正常。我的問題是,我正在調用setPeriod和setInteval from updateScheduler。當updateScheduler被調用時,對象鎖已被鎖定,那麼我打電話的setInterval和updateScheduler但鎖定沒有公佈。我期待的代碼將最終死鎖。但是,這不是爲什麼?