基于线程池的匹配文件数量计算

开发 后端
构建一个新的线程的代价还是有些高的,因为它涉及与操作系统的交互。如果你的程序创建了大量生存期很短的线程,那就应该使用线程池。一个线程池包含大量准备运行的空闲线程。你将一个Runnable对象给线程池,线程池中的一个线程就会调用run方法。当run方法退出时,线程不会死亡,而是继续在池中准备为下一个请求提供服务。

构建一个新的线程的代价还是有些高的,因为它涉及与操作系统的交互。如果你的程序创建了大量生存期很短的线程,那就应该使用线程池。一个线程池包含大量准备运行的空闲线程。你将一个Runnable对象给线程池,线程池中的一个线程就会调用run方法。当run方法退出时,线程不会死亡,而是继续在池中准备为下一个请求提供服务。

执行器(Executor)类有大量用来构建线程池的静态工厂方法,下表给出了一个总结。

 方法 描述 
 newCachedThreadPool 在需要时创建新线程:空闲线程会被保留60秒 
 newFixedThreadPool  池包含固定数量的线程;空闲线程会一直被保留
 newSingleThreadExecutor  只有一个线程的“池”,这个线程顺序执行每一个递交上来的任务
 newScheduledThreadPool  为预定执行而构建的固定线程池
 newSingleThreadScheduledExecutor  为预定执行而构建的单线程“池”

newCachedThreadPool、newFixedThreadPool和newSingleThreadExecutor这三个方法返回ThreadPoolExecutor类(这个类实现了ExecutorService接口)对象。

向线程池提交任务的方法为:将一个实现Runnable或Callable接口的对象提交给ExecutorService:

  1. Future<?> submit(Runable task)  
  2.  
  3. Future<T> submit(Runable task, T result)  
  4.  
  5. Future<t> submit(Callable<T> task) 

线程池会在适当的时候尽早执行提交的任务,调用submit时会返回一个Future对象,用以查询该任务的状态,或者取消该任务。

***个submit方法提交一个Runable对象返回一个Future<?>,可使用该对象调用isDone、cancel、或者isCancelled来查询任务状态。但是此Future对象的get方法在任务完成的时候知识简单的返回null;

第二个版本的submit方法同样提交一个Runable对象,并且返回Future的get方法在任务完成的时候返回传入的result对象;

第三个submit方法提交一个Callable对象,并且返回的Future对象将在计算结构、准备好的时候得到它。

当想要注销一个线程池,可调用shutdown方法,该方法启动该线程池的关闭序列。此时线程池并不是马上就壮烈牺牲了线程也没了,而是等待所以任务都完成以后,线程池中的线程才会死亡,被关闭的执行器不再接受新任务。也可以调用shutdownNow,此时线程池会取消正在排队等待处理的任务并且试图中断正在执行的线程。

下面总结了在使用连接池时应该做的事:

  1. 调用Executor类中静态的newCachedThreadPool或newFixedThreadPool方法。
  2. 调用submit来提交一个Runnable或Callable对象。
  3. 如果希望能够取消任务或如果提交了一个Callable对象,那就保存好返回的Future对象。
  4. 当不想再提交任何任务时调用shutdown。

除了常规的计算匹配文件数量外,这个程序打印出执行过程中池中的***线程数量。但从ExecutorService接口不能得到这个信息。因此,我们必须将pool对象转型成一个ThreadPoolExecutor类对象。

  1. import java.io.*;  
  2. import java.util.*;  
  3. import java.util.concurrent.*;  
  4.  
  5. public class ThreadPoolTest  
  6. {  
  7.    public static void main(String[] args) throws Exception  
  8.    {  
  9.       Scanner in = new Scanner(System.in);  
  10.       System.out.print("Enter base directory (e.g. /usr/local/jdk5.0/src): ");  
  11.       String directory = in.nextLine();  
  12.       System.out.print("Enter keyword (e.g. volatile): ");  
  13.       String keyword = in.nextLine();  
  14.  
  15.       ExecutorService pool = Executors.newCachedThreadPool();  
  16.  
  17.       MatchCounter counter = new MatchCounter(new File(directory), keyword, pool);  
  18.       Future<Integer> result = pool.submit(counter);  
  19.  
  20.       try 
  21.       {  
  22.          System.out.println(result.get() + " matching files.");  
  23.       }  
  24.       catch (ExecutionException e)  
  25.       {  
  26.          e.printStackTrace();  
  27.       }  
  28.       catch (InterruptedException e)  
  29.       {  
  30.       }  
  31.       pool.shutdown();  
  32.  
  33.       int largestPoolSize = ((ThreadPoolExecutor) pool).getLargestPoolSize();  
  34.       System.out.println("largest pool size=" + largestPoolSize);  
  35.    }  
  36. }  
  37.  
  38. /**  
  39.  * This task counts the files in a directory and its subdirectories that contain a given keyword.  
  40.  */ 
  41. class MatchCounter implements Callable<Integer>  
  42. {  
  43.    /**  
  44.     * Constructs a MatchCounter.  
  45.     * @param directory the directory in which to start the search  
  46.     * @param keyword the keyword to look for  
  47.     * @param pool the thread pool for submitting subtasks  
  48.     */ 
  49.    public MatchCounter(File directory, String keyword, ExecutorService pool)  
  50.    {  
  51.       this.directory = directory;  
  52.       this.keyword = keyword;  
  53.       this.pool = pool;  
  54.    }  
  55.  
  56.    public Integer call()  
  57.    {  
  58.       count = 0;  
  59.       try 
  60.       {  
  61.          File[] files = directory.listFiles();  
  62.          ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();  
  63.  
  64.          for (File file : files)  
  65.             if (file.isDirectory())  
  66.             {  
  67.                MatchCounter counter = new MatchCounter(file, keyword, pool);  
  68.                Future<Integer> result = pool.submit(counter);  
  69.                results.add(result);  
  70.             }  
  71.             else 
  72.             {  
  73.                if (search(file)) count++;  
  74.             }  
  75.  
  76.          for (Future<Integer> result : results)  
  77.             try 
  78.             {  
  79.                count += result.get();  
  80.             }  
  81.             catch (ExecutionException e)  
  82.             {  
  83.                e.printStackTrace();  
  84.             }  
  85.       }  
  86.       catch (InterruptedException e)  
  87.       {  
  88.       }  
  89.       return count;  
  90.    }  
  91.  
  92.    /**  
  93.     * Searches a file for a given keyword.  
  94.     * @param file the file to search  
  95.     * @return true if the keyword is contained in the file  
  96.     */ 
  97.    public boolean search(File file)  
  98.    {  
  99.       try 
  100.       {  
  101.          Scanner in = new Scanner(new FileInputStream(file));  
  102.          boolean found = false;  
  103.          while (!found && in.hasNextLine())  
  104.          {  
  105.             String line = in.nextLine();  
  106.             if (line.contains(keyword)) found = true;  
  107.          }  
  108.          in.close();  
  109.          return found;  
  110.       }  
  111.       catch (IOException e)  
  112.       {  
  113.          return false;  
  114.       }  
  115.    }  
  116.  
  117.    private File directory;  
  118.    private String keyword;  
  119.    private ExecutorService pool;  
  120.    private int count;  

原文链接:http://www.cnblogs.com/XL-Liang/archive/2012/06/13/2548327.html

责任编辑:林师授 来源: frogong的博客
相关推荐

2015-07-22 18:07:59

阿里云批量计算

2018-08-15 09:13:27

布线系统线缆用量

2017-11-27 08:38:10

UPS选择容量

2009-08-21 10:50:42

电线电缆材料用量

2024-01-16 10:45:31

C++语言代码

2021-03-01 15:55:17

Go恶意软件勒索软件

2017-01-06 11:18:58

星瑞格

2018-02-28 16:20:57

中科睿芯

2015-05-04 14:46:49

2010-12-23 09:46:03

UNIXSSH

2019-06-06 10:19:33

谷歌开源计算库

2018-01-24 09:27:30

文本分类工具fastText

2024-03-04 09:55:11

开源模型训练

2016-12-06 15:40:08

海量计算星瑞格

2021-09-23 15:55:50

线程池语言公式

2021-04-01 13:05:55

无文件恶意软件威胁情报攻击

2012-07-16 13:17:02

Android恶意软件恶意软件
点赞
收藏

51CTO技术栈公众号