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

上一篇 / 下一篇  2012-06-19 09:28:58 / 个人分类:杂谈

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

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

7j2G}&fi#W0

51Testing软件测试网BNd,f N5gL

  newCachedThreadPool、newFixedThreadPool和newSingleThreadExecutor这三个方法返回ThreadPoolExecutor类(这个类实现了ExecutorService接口)对象。51Testing软件测试网R$DBh t;W%X-r{

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

9}V2b_S)W'h#ox0

  Future<?> submit(Runable task)
z/ob;[ D V+`&GqHk0  Future<T> submit(Runable task, T result)
m q$e.q"m:ZM)g#e;n0  Future<t> submit(Callable<T> task)

J9oH[q0

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

f WYz^"d0

  第一个submit方法提交一个Runable对象返回一个Future<?>,可使用该对象调用isDone、cancel、或者isCancelled来查询任务状态。但是此Future对象的get方法在任务完成的时候知识简单的返回null51Testing软件测试网_^nsd

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

!HIR,|K p0

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

{l%r.y/?D ~9B0

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

4UY E*["g0^0

  下面总结了在使用连接池时应该做的事:51Testing软件测试网qfC^#b{{,V

  1、调用Executor类中静态的newCachedThreadPool或newFixedThreadPool方法。51Testing软件测试网FzlA,Sv+?

  2、调用submit来提交一个Runnable或Callable对象。

F9^7AVM2f%V1~r0

  3、如果希望能够取消任务或如果提交了一个Callable对象,那就保存好返回的Future对象。

+r4c cd,@0

  4、当不想再提交任何任务时调用shutdown。

\ ~B^+nelp0

除了常规的计算匹配文件数量外,这个程序打印出执行过程中池中的最大线程数量。但从ExecutorService接口不能得到这个信息。因此,我们必须将pool对象转型成一个ThreadPoolExecutor类对象。51Testing软件测试网E+B5X5r#~b/N

4FwSLD:Ul&`0P051Testing软件测试网j/Fxf0\1A7W ]&m

51Testing软件测试网x\2M |t7y$SD1c

import java.io.*;51Testing软件测试网jvO%aL
import java.util.*;51Testing软件测试网*wi?-V0?
import java.util.concurrent.*;

#T8jd/a.p051Testing软件测试网Iu6y$b4`"?,o'v

public class ThreadPoolTest51Testing软件测试网,`zX8`6H-T%M ~&Y
{
.I GZ0H,F$ca0   public static void main(String[] args) throws Exception
?$Cr'j_i[0   {
(s]-H9s F$Y Km7v0      Scanner in = new Scanner(System.in);
4\D?"V*e#| e0      System.out.print("Enter base directory (e.g. /usr/local/jdk5.0/src): ");
!U7p-B?T/sv*@0      String directory = in.nextLine();51Testing软件测试网xC.M'U,}N7O){rA Z
      System.out.print("Enter keyword (e.g. volatile): ");
Z;otDb;c0      String keyword = in.nextLine();
51Testing软件测试网hBQ/X Qj+O V

4Ms&F ^.H-Yl{0      ExecutorService pool = Executors.newCachedThreadPool();

ld|7{.P051Testing软件测试网0u0m!T-hD&_qp*|F

      MatchCounter counter = new MatchCounter(new File(directory), keyword, pool);
Ly](dG(^ w U0      Future<Integer> result = pool.submit(counter);

3Oy*N3y:Ny4I$W4@051Testing软件测试网e ]r]q-F

      try
0LEq{qj b6^.^7t4V$m0      {51Testing软件测试网{L df,w7E(Iw)d
         System.out.println(result.get() + " matching files.");51Testing软件测试网4Rq2I8N;SqeA
      }
HWS+_;Q,]ED0      catch (ExecutionException e)
y&f7iY:f9HT0      {51Testing软件测试网W pe#p'Q${m F,P%n
         e.printStackTrace();51Testing软件测试网c.hcg"h%s"w
      }
n#E4Z[ x!~+[0      catch (InterruptedException e)
+tf5l/Jdd0      {
,oN,v cm/Ie0      }
dLR7z8rE0      pool.shutdown();

5L0bay1ne"O051Testing软件测试网)KSqW lp

      int largestPoolSize = ((ThreadPoolExecutor) pool).getLargestPoolSize();
CCi._j0      System.out.println("largest pool size=" + largestPoolSize);
y7UIV,nQF/i0   }51Testing软件测试网"Mu;~J8g
}
51Testing软件测试网7]$_Ts4}!wk-j?/dz

-ovo9?L4d U0/**
vH.XA&Kc!m5Yf0 * This task counts the files in a directory and its subdirectories that contain a given keyword.51Testing软件测试网Ay K;YrH
 */
W(c5G P.\{7d3i2x*k0class MatchCounter implements Callable<Integer>
1w5W7vRS5{ }0{
6v9JuI$G+{0   /**
{{mK,u|z%S'z0    * Constructs a MatchCounter.51Testing软件测试网DQ Eur1D#e
    * @param directory the directory in which to start the search51Testing软件测试网ii0m_.T-P zH
    * @param keyword the keyword to look for
#tJ x,R}!VMlZ)I0    * @param pool the thread pool for submitting subtasks51Testing软件测试网#t,~,Y5]4xK:}
    */51Testing软件测试网{"AR%kG5B a
   public MatchCounter(File directory, String keyword, ExecutorService pool)
V.r.bj/O f;R ]3i0   {
C p)M;c$?$Ho6XA0      this.directory = directory;
9}(P?[ @(m)a0      this.keyword = keyword;
&X NJ+K"Pn6H0      this.pool = pool;
-a[}7ai!Bu"R(Z0   }

D+W_*V0`-M0

!h'yk,? m0   public Integer call()
I%K;g hC8b z0   {51Testing软件测试网p MgHkU
      count = 0;51Testing软件测试网#IK*d&xj~)@
      try
*YT Ay5NR7^CzNL0      {51Testing软件测试网&L NGKF,B_O
         File[] files = directory.listFiles();
(Cw6LqUpY"F.Bt(l0         ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();

5{4zzWZ9v051Testing软件测试网D WZ] q8{

         for (File file : files)51Testing软件测试网!|Bw%z)_ \ ?j aZ
            if (file.isDirectory())
Jv*gw"f!d9hR0            {51Testing软件测试网Y(l&Sw!VoP#y
               MatchCounter counter = new MatchCounter(file, keyword, pool);
9}E(E6l:r.Db0               Future<Integer> result = pool.submit(counter);51Testing软件测试网b:K.uL On5}6A
               results.add(result);
4z2r.K e5if7nZ0            }51Testing软件测试网re&I6J8X%i
            else51Testing软件测试网+h1[9LT)E%N4M?/J0G
            {51Testing软件测试网d)a C3sv7w
               if (search(file)) count++;51Testing软件测试网7e [I|*@u}+w
            }

6|0| P%{9n-k{`0

1JCTK$p e b0         for (Future<Integer> result : results)51Testing软件测试网TLEf&v6G
            try51Testing软件测试网'Ls'\$}TTdh
            {
_{3Pb;kz0               count += result.get();
&Gp[@.T([ z,wl0            }
0zF:eNJhys~p0            catch (ExecutionException e)51Testing软件测试网2te2o$cAV`4S:oSA
            {51Testing软件测试网YME4Z%Pv
               e.printStackTrace();
*E!R(~)[4Ji+]Y0            }51Testing软件测试网:c"W)VvPUS8l&^8v)B
      }51Testing软件测试网SDK k;^$U9r
      catch (InterruptedException e)
G#]Ch V0      {51Testing软件测试网3Y,VD%gq4yf `%@^
      }
'X&V[dfp}"Pl~0      return count;51Testing软件测试网:n {e _-|w
   }
51Testing软件测试网9_@_%L0f$n0]#OH{c

{oS`ar6~0   /**
UM~-M A.vs g"|0    * Searches a file for a given keyword.51Testing软件测试网YDeU@4Y8a
    * @param file the file to search
m6h6{D0p O"PZ$D0    * @return true if the keyword is contained in the file51Testing软件测试网TXm#opjO"[7\+n j|
    */51Testing软件测试网M4^#|I y dE\
   public boolean search(File file)51Testing软件测试网YI;Iv*X x/Se
   {
!DZ`)PP'Yy j0      try
~E5e&L`hf-K0      {51Testing软件测试网 SB:{:I*z
         Scanner in = new Scanner(new FileInputStream(file));51Testing软件测试网5P b3O)[5C6UhVm"Q
         boolean found = false;51Testing软件测试网}*?"dRK k
         while (!found && in.hasNextLine())
'G7lk y~&A-_n"Oi b0         {51Testing软件测试网(y/} n2_*V,ov;\*e;C;s
            String line = in.nextLine();
R!e^wE@0            if (line.contains(keyword)) found = true;51Testing软件测试网2Sf0t#X.q9W;k
         }
2e2l w Z X p9X)v m t+J0         in.close();
5I9j2U HO0         return found;51Testing软件测试网4I/|'N J(Aux:i^&k
      }
mQ9d8Nt/A3JkZ0      catch (IOException e)51Testing软件测试网p8K h!@ c[%v9b Q
      {
L4D3ce!Z [k/f0         return false;
2]P ^B/p0      }
EQ:x|6DQ!K#w0   }
51Testing软件测试网\;x!f_T7F/_3A},e8nG

51Testing软件测试网2o+U;Z+d)u0V%|R1I

   private File directory;51Testing软件测试网R/n5D)C*} [:B9E
   private String keyword;51Testing软件测试网2YO5e:{A-Q N
   private ExecutorService pool;51Testing软件测试网d~q#MCls
   private int count;
s;Ey!f/`V0}
51Testing软件测试网-}d0~&R%o


TAG:

 

评分:0

我来说两句

Open Toolbar