---
title: "利用线程池实现文件搜索"
author: "w2c2y2"
date: "2009-10-04T18:22:21Z"
tags: ["Java", "thread", "多线程", "工作"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2009-10-04T18:22:21Z"
id: 481759
url: "https://w2c2y2.iteye.com/blog/481759"
---

1、类MulFilesFind：

 

package cy.thread.pool;

import java.io.File;  
import java.util.concurrent.ArrayBlockingQueue;  
import java.util.concurrent.ThreadPoolExecutor;  
import java.util.concurrent.TimeUnit;

public class MulFilesFind {  
   
 public static String filename;  
 private ThreadPoolExecutor threadPool;  
   
 public ThreadPoolExecutor getThreadPool() {  
  return threadPool;  
 }

 public void setThreadPool(ThreadPoolExecutor threadPool) {  
  this.threadPool = threadPool;  
 }

 public MulFilesFind(String filename){  
  this.filename = filename;  
  threadPool = new ThreadPoolExecutor(50,100,15,TimeUnit.SECONDS,new ArrayBlockingQueue(100),new ThreadPoolExecutor.CallerRunsPolicy());  
 }

 public void findFiles(String path){  
  File file = new File(path);  
    
  if(file.isDirectory()){  
   File\[] listfiles = file.listFiles();  
   if(null != listfiles){  //经过测试，发现如果文件夹下没有文件，那么会报空指针异常。  
    for(int i=0; i&lt;listfiles.length; i++){  
     threadPool.execute(new FilesHandler(listfiles\[i])); //往工作队列中添加任务  
    }  
   }

  }

 }  
   
   
   
 /*  
  *  
  * 内部类  
  *   
  \*/  
 class FilesHandler implements Runnable{  
  private File file;  
    
  public FilesHandler(File file){  
   this.file = file;  
  }

  public void run() {  
   // TODO Auto-generated method stub  
   String \_filename = file.getName();  
   String \_filepath = file.getPath();  
//   System.out.println(\_filepath);  
   if(filename.equals(\_filename) && file.isFile()){  
    System.out.println(\_filepath);  
   }  
   else if(file.isDirectory()){  
    findFiles(\_filepath);  
   }  
  }

 }  
   
}

 

 

2、测试主函数：

package cy.thread.pool;

import java.io.File;

public class MainTest {  
 /*  
  *  
  *  
  * 利用我们的线程池来实现我们的文件搜索功能。  
  *  
  \*/  
 public static void main(String ad\[]){  
    
  MulFilesFind find = new MulFilesFind("新建文本文档.txt");  
    
  find.findFiles("E:");  
    
 }  
}