通过公开调用避免相互协作的对象之间产生死锁

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;
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_37632716/article/details/119080980
今日推荐