不支持关闭的生产者-消费者日志服务

public class LogWriter{
    
    
  private final BlockinQueue<String> queue;
  private final LoggerThread logger;

  public LogWriter(Writer writer){
    
    
    this.queue = new LinkedBlockingQueue<String>(CAPACITY);
    this.logger = new LoggerThread(writer);
  }

  public void start(){
    
    
    logger.start();
  }

  private class LoggerThread extends Thread{
    
    
    try{
    
    
      while(true){
    
    
        writer.println(queue.take());
      }
    }catch(InterruptedException ignored){
    
    
    }finally{
    
    
      writer.close();
    }
  }
}



//可靠的取消操作
public class LogService{
    
    
  private final BlockingQueue<String> queue;
  private final LoggerThread loggerThread;
  private boolean isShutDown;
  private int reservations;
  ...
  public void start(){
    
    
    loggerThread.start();
  }

  publiv void stop(){
    
    
    synchronized(this){
    
    
      isShutDown = ture;
    }
    loggerThread.interrupt();
  }

  public void log(String msg){
    
    
    synchronized(this){
    
    
      if(isShutDown)
        throw new IllegalStateStateException();
    }
    queue.put(msg);
  }

  private class LoggerThread extends Thread{
    
    
    publiv void run(){
    
    
      try{
    
    
        synchronized(this){
    
    
          if(isShutDown && reservations == 0){
    
    
            break;
          }
        }
        String msg = queue.take();
        synchronized(this){
    
    --reservations;}
        writer.println(msg);

      }catch(InterruptedException e){
    
    
        
      }finally{
    
    
        writer.close();
      }
    }

  }
}

猜你喜欢

转载自blog.csdn.net/weixin_37632716/article/details/118529379