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;
}
}
}
线程池应用小示例
最新推荐文章于 2024-02-10 15:55:40 发布