class Taxi{
private final Dispatcher dispatcher;
public Taxi(Dispatcher dispatcher){
this.dispatcher = dispatcher;
}
public synchronized point getLocation(){
return location;
}
public synchronized void setLocation(Point location){
this.location = location;
if(location.equals(destination)){
dispatcher.notifyAvailable(this);
}
}
}
class Dispatcher{
private final Set<Taxi> taxis;
private final Set<Taxi> availableTaxis;
public Dispatcher(){
taxis = new HashSet<Taxi>();
availableTaxis = new HashSet<Taxi>();
}
public synchronized void notifyAvailable(Taxi taxi){
availableTaxis.add(taxi);
}
public synchronized Image getImage(){
Image image = new Image();
for(Taxi t:taxis){
image.drawMarker(t.getLocation());
}
return image;
}
}
如果在持有锁时调用某个外部方法,那么将出现活跃性问题,在外部方法中可能会获得其他锁,这可能会产生死锁,活着阻塞时间过长,导致其他线程无法及时获得当前被持有的锁