synchronized 方法中的 synchronized(this) 块
synchronized(this) block within the synchronized method
以下是 java 并发实践 一书中讨论 公开调用 的代码片段。我没有得到的一点是 setLocation 方法的声明方式,它已经同步并在同一方法中再次调用 synchronized(this) 块,为什么这样?是类型错误吗? synchronized 方法已经锁定了这个方法,那为什么还要锁定同一个对象?
@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);
}
}
这是书中的一个错误。参见 the errata
In Listing 10.6, Taxi.setLocation should not be a synchronized method. (The synchronized block in its body is correct, however.)
以下是 java 并发实践 一书中讨论 公开调用 的代码片段。我没有得到的一点是 setLocation 方法的声明方式,它已经同步并在同一方法中再次调用 synchronized(this) 块,为什么这样?是类型错误吗? synchronized 方法已经锁定了这个方法,那为什么还要锁定同一个对象?
@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);
}
}
这是书中的一个错误。参见 the errata
In Listing 10.6, Taxi.setLocation should not be a synchronized method. (The synchronized block in its body is correct, however.)