如果我的文件夹下共有五个空文件,2个txt文档,那么会产生6个线程,但是为什么在下面代码中count只出现了5次?每个线程都会运行到这段代码的啊。
for (Future<Integer> futureItem : results) {
count += futureItem.get();
System.out.println("count出现了一次");
}
运行结果如下:
代码如下:
public class ThreadPoolTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("please enter the starting file:");
String fileName = sc.nextLine();
System.out.println("please enter what you wang to find:");
String keybroad = sc.nextLine();
File file = new File(fileName);
ExecutorService pool = Executors.newCachedThreadPool();
MathCounter mathCounter = new MathCounter(file, keybroad,pool);
Future<Integer> future = pool.submit(mathCounter);
try {
System.out.println("包含关键字的文件的个数:"+ future.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MathCounter implements Callable<Integer>{
File file;
String keybroad;
ExecutorService pool;
List<Future<Integer>> results = new ArrayList<>();
public MathCounter(File file, String keybroad, ExecutorService pool) {
// TODO Auto-generated constructor stub
this.file = file;
this.keybroad = keybroad;
this.pool = pool;
}
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
int count=0;
File[] files = file.listFiles();
String string;
for (File file_search : files) {
if (file_search.isDirectory()) {
MathCounter mathCounter = new MathCounter(file_search, keybroad,pool);
Future<Integer> future = pool.submit(mathCounter);
results.add(future);
}else {
if (file_search.canRead()) {
boolean flag = false;
int numberLine = 0;
Scanner scanner = new Scanner(file_search);
while(scanner.hasNextLine()){
numberLine++;
string = scanner.nextLine();
if (string.contains(keybroad)) {
flag = true;
System.out.printf("%s: %d, %s\n", file_search.getName(), numberLine, string);
}
}
if (flag == true) {
count++;
}
}
}//else
}
for (Future<Integer> futureItem : results) {
count += futureItem.get();
System.out.println("count出现了一次");
}
return count;
}
}