1.我使用线程池对某一个文件下统计所有文件信息,却出现不用结果
在使用线程池的时候,只统计到了文件夹的信息,没有统计到文件的信息,
不使用线程池的时候,统计了全部信息。大家能帮忙看下吗
public static ExecutorService executorService = Executors.newFixedThreadPool(100);
public static List<Callable<Integer>> tasks = new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
Dome dome = new Dome();
long start = System.currentTimeMillis();
String addr = "D:\\";
dome.file(addr);
executorService.invokeAll(tasks);
executorService.shutdown();
final int[] i = {0};
map.forEach((k, v) -> {
i[0]++;
System.out.println(i[0] + " " + k + " " + v);
});
long end = System.currentTimeMillis();
System.out.println("耗时:" + TimeUnit.SECONDS.convert(end - start, TimeUnit.SECONDS));
}
public void file(String addr) throws InterruptedException {
File file = new File(addr);
if (file != null) {
if (file.isDirectory()) {
map.put(file.getPath() + "是文件夹:", "一共:" + "个文件");
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File file1 : files) {
Callable<Integer> task = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
file(file1.getPath());
return 1;
}
};
tasks.add(task);
}
}
} else {
map.put(file.getPath() + "是文件:", "文件大小是:" + file.length());
}
}
}
// 代码直接可以运行 可以对线程池进行注释。
结果为啥不一样这个我看不出,但是哥们你运行的时候没有线程安全问题么,tasks一边遍历,一边加元素
用线程池的时候,你task的call没执行,而且你这个代码自己都没用到线程池,你定义了又不用