1_基础知识_chapter05_基础构建模块_3_阻塞队列和生产者-消费者模式

  • BlockingQueue接口和生产者-消费者模式

    (1) 生产者-消费者模式消除了生产者类和消费者类之间的代码依赖性: 生产者将数据放入队列; 消费者从队列中取数据

    (2) 阻塞队列提供了可阻塞的put和take方法, 和支持定时的offer和poll方法

    (3) 队列可以有界也可以无界(在构造函数中指定, 但其实无界的阻塞队列也有最大值Integer.MAX_VAL)

    (4) BlockingQueue是一个接口, 几个实现是ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue。

    其中, ArrayBlockingQueue和LinkedBlockingQueue分别与ArrayList和LinkedList相似, 是FIFO队列;

    PriorityBlockingQueue是优先级队列;

    SynchronousQueue比较特殊, 它维护一组线程,没有存储功能, 生产者和消费者的put和take会一直阻塞直到另一个线程准备好参与到交付过程中

    (5) 示例

    桌面搜索: 生产者线程负责找到所有文件, 消费者线程负责对文件建立索引

      public class ProducerConsumer {
    
          static class FileCrawler implements Runnable {
    
              private final BlockingQueue<File> fileQueue;
              private final FileFilter fileFilter;
              private final File root;
    
              public FileCrawler(BlockingQueue<File> fileQueue, final FileFilter fileFilter, File root) {
    
                  this.fileQueue = fileQueue;
                  this.root = root;
    
                  this.fileFilter = new FileFilter() {
                      public boolean accept(File f) {
    
                          return f.isDirectory() || fileFilter.accept(f);
                      }
                  };
              }
    
              private boolean alreadyIndexed(File f) {
                  return false;
              }
    
              public void run() {
                  try {
                      crawl(root);
                  } catch (InterruptedException e) {
                      Thread.currentThread().interrupt();
                  }
              }
    
              private void crawl(File root) throws InterruptedException {
                  
                  File[] entries = root.listFiles(fileFilter);
                  if (entries != null) {
                      for (File entry : entries)
                          if (entry.isDirectory()) {
                              crawl(entry);
                          } else if (!alreadyIndexed(entry)) {
                              fileQueue.put(entry);
                          }
                      }                        
                  }
              }
          }
    
          static class Indexer implements Runnable {
              private final BlockingQueue<File> queue;
    
              public Indexer(BlockingQueue<File> queue) {
                  this.queue = queue;
              }
    
              public void run() {
                  try {
                      while (true) {
                          indexFile(queue.take());
                      }
                  } catch (InterruptedException e) {
                      Thread.currentThread().interrupt();
                  }
              }
    
              public void indexFile(File file) {
                  // Index the file...
              }
          }
    
          private static final int BOUND = 10;
          private static final int N_CONSUMERS = Runtime.getRuntime().availableProcessors();
    
          public static void startIndexing(File[] roots) {
    
              BlockingQueue<File> queue = new LinkedBlockingQueue<>(BOUND);
    
              FileFilter filter = new FileFilter() {
                  public boolean accept(File file) {
    
                      return true;
                  }
              };
    
              for (File root : roots) {
                  new Thread(new FileCrawler(queue, filter, root)).start();
              }
    
              for (int i = 0; i < N_CONSUMERS; i++) {
                  new Thread(new Indexer(queue)).start();
              }
          }
      }
    

    (6) 串行线程封闭

    线程封闭对象只能由单个线程拥有, 但可以通过安全发布该对象转移所有权: 这种安全的发布确保了对象状态对于新的所有者可见, 并且由于最初的所有者不会访问它, 因此对象被封闭在新的线程内。

    阻塞队列简化了这项工作

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 阻塞队列提供了可阻塞的put 和take方法, 以及支持定时的offer和poll方法。如果队列已经满了, 那么p...
    好好学习Sun阅读 1,696评论 0 4
  • java笔记第一天 == 和 equals ==比较的比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量...
    jmychou阅读 1,526评论 0 3
  • 进程和线程 进程 所有运行中的任务通常对应一个进程,当一个程序进入内存运行时,即变成一个进程.进程是处于运行过程中...
    胜浩_ae28阅读 5,153评论 0 23
  • 注意:该随笔内容完全引自http://wsmajunfeng.iteye.com/blog/1629354,写的很...
    爱斯基摩白阅读 392评论 0 0
  • 今天给一奔驰换正时链轮 严格按照维修手册操作 每一颗螺丝 都用扭力扳手打扭力 总结 维修有标准 有了标准 心里有数
    刘磊stely阅读 189评论 0 0