A.使用阻塞队列存储任务:Runnable,Callable,FutureTask
B.线程池从队列取任务执行:put(),take()
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; public class MatchCounter implements Callable<Integer> { public static void main(String[] args) { File directory = new File("D:\\project\\sis\\branches\\uat\\play\\test"); String keyword = "class"; //线程池 ExecutorService pool = Executors.newCachedThreadPool(); MatchCounter counter = new MatchCounter(directory, keyword, pool); Future<Integer> result = pool.submit(counter); try { System.out.println(result.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) {} pool.shutdown(); //获取线程池同时存在线程的峰值 ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)pool; int largest = threadPoolExecutor.getLargestPoolSize(); System.out.println("largest pool size = " + largest); } public MatchCounter(File directory, String keyword, ExecutorService threadPool) { this.searchDir = directory; this.keyword = keyword; this.pool = threadPool; this.count = 0; } @Override public Integer call() throws Exception { ArrayList<Future<Integer>> resultList = new ArrayList<>();//保存结果集 for(File file : searchDir.listFiles()){ if(file.isDirectory()) { MatchCounter counter = new MatchCounter(file, keyword, pool); Future<Integer> result = pool.submit(counter);//提交新的任务 resultList.add(result); } else { if(search(file)) count++; } } for(Future<Integer> result : resultList) { count += result.get();//递归 } return count; } private boolean search(File file) { try { Scanner in = new Scanner(new FileInputStream(file)); boolean found = false; while(!found && in.hasNextLine()) { String line = in.nextLine(); if(line.contains(keyword)) found = true; } in.close(); return found; } catch (FileNotFoundException e1) { return false; } } private int count; private File searchDir; private String keyword; private ExecutorService pool; }