毒丸对象关闭生产者消费者服务

public class CrawlerThread extends Thread{
    
    
  public void run(){
    
    
    try{
    
    
      crawl(root);
    }catch(){
    
    }finally{
    
    
      while(true){
    
    
        try{
    
    
          queue.put(POISON);
        }catch(InterruptedException el){
    
    //重新尝试}
      }
    }
  }

  public void crawl(File root) throws InterruptedException{
    
    
  ...
  }
}

public class IndexerThread extends Thread{
    
    
  public void run(){
    
    
    try{
    
    
      while(true){
    
    
        File file = queue.take();
        if(file == POISON){
    
    
          break;
        }else{
    
    
          indexFile(file);
        }
      }
    }catch(InterruptedException consumed){
    
    }
  }
}

public class IndexingService{
    
    
  private static final File POISON = new File("");
  private final IndexerThread consumer = new IndexerThread();
  private final CrawlerThread producer = new CrawlerThread();
  private final BlockingQueue<File> queue;
  private final FileFilter fileFilter;
  private final File root;

  class CrawlerThread extends Thread{
    
    };

  class IndexerThread extends Thread();

  public void start(){
    
    
    producer.start();
    consumer.start();
  }

  public void stop(){
    
    
    producer.interrupt();
  }

  public void awaitTermination() throws InterruptedException{
    
    
    consumer.join();
 }
  

}

猜你喜欢

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