Java中使用阻塞队列控制线程集实例

 更新时间:2015年01月15日 11:08:18   投稿:junjie  
这篇文章主要介绍了Java控制阻塞队列线程集实例,本文用一个程序展示了如何使用阻塞队列来控制线程集,程序功能是在一个目录及它的所有子目录下搜索所有文件,打印出包含指定关键字的文件列表,需要的朋友可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

队列以一种先进先出的方式管理数据。如果你试图向一个已经满了的阻塞队列中添加一个元素,或是从一个空的阻塞队列中移除一个元素,将导致线程阻塞。在多线程进行合作时,阻塞队列是很有用的工具。工作者线程可以定期的把中间结果存到阻塞队列中。而其他工作者线程把中间结果取出并在将来修改它们。队列会自动平衡负载。如果第一个线程集运行的比第二个慢,则第二个线程集在等待结果时就会阻塞。如果第一个线程集运行的快,那么它将等待第二个线程集赶上来。

下面的程序展示了如何使用阻塞队列来控制线程集。程序在一个目录及它的所有子目录下搜索所有文件,打印出包含指定关键字的文件列表。

java.util.concurrent包提供了阻塞队列的4个变种:LinkedBlockingQueue、ArrayBlockingQueue、PriorityBlockingQueue和DelayQueue。我们用的是ArrayBlockingQueue。ArrayBlockingQueue在构造时需要给定容量,并可以选择是否需要公平性。如果公平参数被设置了,等待时间最长的线程会优先得到处理。通常,公平性会使你在性能上付出代价,只有在的确非常需要的时候再使用它。

生产者线程枚举在所有子目录下的所有文件并把它们放到一个阻塞队列中。这个操作很快,如果队列没有设上限的话,很快它就包含了没有找到的文件。

我们同时还启动了大量的搜索线程。每个搜索线程从队列中取出一个文件,打开它,打印出包含关键字的所有行,然后取出下一个文件。我们使用了一个小技巧来在工作结束后终止线程。为了发出完成信号,枚举线程把一个虚拟对象放入队列。(这类似于在行李输送带上放一个写着“最后一个包”的虚拟包。)当搜索线程取到这个虚拟对象时,就将其放回并终止。

注意,这里不需要人任何显示的线程同步。在这个程序中,我们使用队列数据结构作为一种同步机制。

复制代码 代码如下:

import java.io.*; 
import java.util.*; 
import java.util.concurrent.*; 

public class BlockingQueueTest 

   public static void main(String[] args) 
   { 
      Scanner in = new Scanner(System.in); 
      System.out.print("Enter base directory (e.g. /usr/local/jdk1.6.0/src): "); 
      String directory = in.nextLine(); 
      System.out.print("Enter keyword (e.g. volatile): "); 
      String keyword = in.nextLine(); 

      final int FILE_QUEUE_SIZE = 10; 
      final int SEARCH_THREADS = 100; 

      BlockingQueue<File> queue = new ArrayBlockingQueue<File>(FILE_QUEUE_SIZE); 

      FileEnumerationTask enumerator = new FileEnumerationTask(queue, new File(directory)); 
      new Thread(enumerator).start(); 
      for (int i = 1; i <= SEARCH_THREADS; i++) 
         new Thread(new SearchTask(queue, keyword)).start(); 
   } 

/** 
 * This task enumerates all files in a directory and its subdirectories. 
 */
class FileEnumerationTask implements Runnable 

   /** 
    * Constructs a FileEnumerationTask. 
    * @param queue the blocking queue to which the enumerated files are added 
    * @param startingDirectory the directory in which to start the enumeration 
    */
   public FileEnumerationTask(BlockingQueue<File> queue, File startingDirectory) 
   { 
      this.queue = queue; 
      this.startingDirectory = startingDirectory; 
   } 

   public void run() 
   { 
      try
      { 
         enumerate(startingDirectory); 
         queue.put(DUMMY); 
      } 
      catch (InterruptedException e) 
      { 
      } 
   } 

   /** 
    * Recursively enumerates all files in a given directory and its subdirectories 
    * @param directory the directory in which to start 
    */
   public void enumerate(File directory) throws InterruptedException 
   { 
      File[] files = directory.listFiles(); 
      for (File file : files) 
      { 
         if (file.isDirectory()) enumerate(file); 
         else queue.put(file); 
      } 
   } 

   public static File DUMMY = new File(""); 

   private BlockingQueue<File> queue; 
   private File startingDirectory; 

/** 
 * This task searches files for a given keyword. 
 */
class SearchTask implements Runnable 

   /** 
    * Constructs a SearchTask. 
    * @param queue the queue from which to take files 
    * @param keyword the keyword to look for 
    */
   public SearchTask(BlockingQueue<File> queue, String keyword) 
   { 
      this.queue = queue; 
      this.keyword = keyword; 
   } 

   public void run() 
   { 
      try
      { 
         boolean done = false; 
         while (!done) 
         { 
            File file = queue.take(); 
            if (file == FileEnumerationTask.DUMMY) 
            { 
               queue.put(file); 
               done = true; 
            } 
            else search(file);             
         } 
      } 
      catch (IOException e) 
      { 
         e.printStackTrace(); 
      } 
      catch (InterruptedException e) 
      { 
      }       
   } 

   /** 
    * Searches a file for a given keyword and prints all matching lines. 
    * @param file the file to search 
    */
   public void search(File file) throws IOException 
   { 
      Scanner in = new Scanner(new FileInputStream(file)); 
      int lineNumber = 0; 
      while (in.hasNextLine()) 
      { 
         lineNumber++; 
         String line = in.nextLine().trim(); 
         if (line.contains(keyword)) System.out.printf("%s:%d    %s%n", file.getPath(), lineNumber, line); 
      } 
      in.close(); 
   } 

   private BlockingQueue<File> queue; 
   private String keyword; 
}

相关文章

  • 详解基于java的Socket聊天程序——服务端(附demo)

    详解基于java的Socket聊天程序——服务端(附demo)

    这篇文章主要介绍了详解基于java的Socket聊天程序——服务端(附demo),具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
    2016-12-12
  • Java实现本地缓存的方式汇总

    Java实现本地缓存的方式汇总

    引入缓存,主要用于实现系统的高性能,高并发,这篇文章主要介绍了Java实现本地缓存的几种方式,本文结合示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-07-07
  • SpringBoot配置文件导入方法详细讲解

    SpringBoot配置文件导入方法详细讲解

    Spring Boot虽然是Spring的衍生物, 但默认情况下Boot是不能直接使用Spring的配置文件的, 我们可以通过两种方式导入Spring的配置
    2022-10-10
  • Java接口异步调用优化技巧详解

    Java接口异步调用优化技巧详解

    本文详细介绍了在Java开发中,如何通过异步调用等技巧来优化接口的性能,有效避免阻塞和提高并发处理能力,提升系统的稳定性和响应速度
    2023-05-05
  • Java利用Request请求获取IP地址的方法详解

    Java利用Request请求获取IP地址的方法详解

    在开发中我们经常需要获取用户IP地址,通过地址来实现一些功能,下面这篇文章主要给大家介绍了关于Java利用Request请求获取IP地址的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧。
    2017-10-10
  • Maven 错误找不到符号的解决方法

    Maven 错误找不到符号的解决方法

    这篇文章主要介绍了Maven 错误找不到符号的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • Java中的@SneakyThrows注解详解

    Java中的@SneakyThrows注解详解

    这篇文章主要介绍了Java中的@SneakyThrows注解详解,@SneakyThrows将当前方法抛出的异常,包装成RuntimeException,骗过编译器,使得调用点可以不用显示处理异常信息,需要的朋友可以参考下
    2023-10-10
  • Spring Boot console log 格式自定义方式

    Spring Boot console log 格式自定义方式

    这篇文章主要介绍了Spring Boot console log 格式自定义方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • springcloud-gateway集成knife4j的示例详解

    springcloud-gateway集成knife4j的示例详解

    这篇文章主要介绍了springcloud-gateway集成knife4j的示例详解,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-03-03
  • Java接口名称冲突问题的讲解

    Java接口名称冲突问题的讲解

    今天小编就为大家分享一篇关于Java接口名称冲突问题的讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-04-04

最新评论


http://www.vxiaotou.com