我有一个派生类,由于某种原因,我必须使这个类的两个方法同步,以防止它们同时执行。其中一种方法是重写方法。父方法未同步。
是否可以同步重写方法?
答案 0 :(得分:2)
答案 1 :(得分:0)
简单地创建方法synchronized
并不能消除2个线程可能交错的可能性。请考虑以下示例,其中drive()
方法调用addGas()
。在drive()
子类中同步Car
会使2个线程重叠的可能性。
public class Vehicle {
private int fuel;
public void addGas() {
// add gas to car
// update database with new value
}
public void drive() {
// add gas for low fuel levels
if (fuel < 10) {
addGas();
}
}
}
public class Car extends Vehicle {
@Override
public synchronized void drive() {
// do car specific init here
super.drive();
while (true) {
// cruise control for 1 second
Thread.sleep(1000);
if (fuel < 15) {
addGas(); // More than one thread might be calling
} // at the same time!
}
}
}
在此示例中,父类Vehicle
具有名为addGas()
的辅助方法。问题是这个方法不同步,所以另一个线程可能在Car
类也在调用它的同时调用它。
换句话说,简单地创建子类方法synchronized
并不一定能消除2个线程交错的可能性。