线程池

package org.chapter.thread;


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;


/**
 * 
 * 还是打印目录的示列 前面的程序列子产生了大量的声明期很短的线程,。 每个目录产生一个线程,现在程序适用了一个线程池来运行任务
 * 处于信息方面的考虑,这个程序打印出执行中池中最大的线程数 但是不能通过 ExecutorService 这个借口得到这一信息 因此
 * 必须将该pool对象转型为ThreadPoolExcutor类对象
 * 
 */
public class ThreadPoolTest {


public static void main(String[] args) throws InterruptedException, ExecutionException {

Scanner in=new Scanner(System.in);
System.out.print("请输入文件目录:");
String directory=in.nextLine();
System.out.print("请输入关键字:");
String keyword=in.nextLine();
//关键步骤  创建线程池
ExecutorService pool =Executors.newCachedThreadPool();
MatchCounter counter=new MatchCounter(new File(directory), keyword, pool);
Future<Integer> result=pool.submit(counter);
System.out.println("matching files:"+result.get());


//终止
pool.shutdown();


int largstPoolSize=((ThreadPoolExecutor)pool).getLargestPoolSize();
System.out.println("largest pool size ="+largstPoolSize);
}
}


class MatchCounter implements Callable<Integer> {
// 文件目录
private File directory;
// 关键字匹配
private String keyword;
// 线程池 执行器
private ExecutorService pool;
private int count;


public MatchCounter(File directory, String keyword, ExecutorService pool) {


this.directory = directory;
this.keyword = keyword;
this.pool = pool;
}


@Override
public Integer call() throws Exception {


count = 0;
File[] files = directory.listFiles();
ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();
for (File file : files) {
if (file.isDirectory()) {
MatchCounter counter = new MatchCounter(file, keyword, pool);
Future<Integer> result = pool.submit(counter);
results.add(result);
} else {
if (search(file))
count++;
}


for (Future<Integer> result : results) {
count += result.get();
}
}


return count;
}


public 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 e) {
// TODO Auto-generated catch block


return false;
}


}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值