class Taxi{
private final Dispatcher dispatcher;
...
public synchronized Point getLocation(){
return location;
}
public void setLocation(Point location){
boolean reachedDestination;
synchronized(this){
this.location = location;
reachedDestination = location.equeals(destination);
}
if(reachedDestination){
dispatcher.notifyAvailable(this);
}
}
}
class Dispatcher{
private final Set<Taxi> taxis;
private final Set<Taxi> availableTaxis;
...
public synchronized void notifyAvailable(Taxi taxi){
availableTaxis.add(taxi);
}
public Image getImage(){
Set<Taxi> copy;
synchronized(this){
copy = new HashSet<Taxi>(taxis);
}
Image image = new Image();
for(Taxi t: copy){
image.drawMarker(t.getLocation());
}
return image;
}
}
通过公开调用避免相互协作的对象之间产生死锁
最新推荐文章于 2022-04-01 19:04:17 发布