线程池应用小示例

 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
public class ThreadPoolTest {
public static void main(String[] args) {
  String directory = "src/thread/pool";
  String keyWord = "wujinbo";
  ExecutorService pool = Executors.newCachedThreadPool();
  SearchTask counter = new ThreadPoolTest().new SearchTask(new File(directory), keyWord);
  Future<Integer> result = pool.submit(counter);
  try {
   System.out.println(result.get() + "--> 找到了匹配的字符串.");
  } catch (Exception e) {
   System.err.println("出现异常");
  }
  int size = ((ThreadPoolExecutor) pool).getLargestPoolSize();
  System.out.println("最大线程数为:" + size);
  pool.shutdown();
}
class SearchTask implements Callable<Integer> {
  private File dir;
  private String keyWord;
  private int count;
  public SearchTask(File directory, String keyWord) {
   this.dir = directory;
   this.keyWord = keyWord;
  }
  /**
   * 实现Callable接口中的方法:在某一目录下查找指定的关键字
   */
  public Integer call() throws Exception {
   count = 0;
   try {
    File[] files = dir.listFiles();
    for (File file : files) {
     if (this.search(file)) {
      count = 1;
     }
    }
   } catch (Exception e) {
    count = 0;
   }
   return count ;
  }
  /**
   * 在一个文件中查找指定的字符串
   * @param file
   * @return
   */
  public boolean search(File file) {
   boolean found = false;
   try {
    Scanner in = new Scanner(new FileInputStream(file));
    while (!found && in.hasNextLine()) {
     String line = in.nextLine();
     if (line.contains(keyWord)) {
      found = true;
      in.close();
      break;
     }else{
      continue ;
     }
    }
   } catch (FileNotFoundException e) {
    found = false;
   }
   return found;
  }
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值