以下是Java并发实践书中讨论开放调用时的代码片段。我没有得到的一点是声明 setLocation 方法的方式,它已经同步并再次在同一方法中调用 synchronized(this) 块,为什么这样?是类型错误吗?同步方法已经持有该方法的锁,那么为什么还要为同一个对象呢?
@ThreadSafe
class Taxi {
@GuardedBy("this") private Point location, destination;
private final Dispatcher dispatcher;
...
public synchronized Point getLocation() {
return location;
}
public synchronized void setLocation(Point location) {
boolean reachedDestination;
synchronized (this) {
this.location = location;
reachedDestination = location.equals(destination);
}
if (reachedDestination)
dispatcher.notifyAvailable(this);
}
}