多线程参考核心代码
public void threadTest() {
CountDownLatch latch = new CountDownLatch(threadCount);
//初始化线程数量,开启5个线程
for (int i = 0; i < 5; i++) {
int finalI = i;
ThreadUtil.execute(() -> {
try {
logger.info("线程启动,线程序列为 i = " + finalI);
//开始操作文件
//这里写你的逻辑代码
} catch (Exception e) {
//异常处理
throw new RuntimeException(e.getMessage());
} finally {
logger.info("线程结束,线程序列为 i = " + finalI);
latch.countDown();
}
});
}
latch.await();
}
多线程读取指定目录下的文件
// 用于记录已上传的文件,如果文件实在太多,可以考虑redis或者数据库存放,不同map
private static final Map<String, Boolean> processedFilesMap = new ConcurrentHashMap<>();
public void threadTest() {
File directory = new File("D:/img/test/001");//获取到所有目录的情况
CountDownLatch latch = new CountDownLatch(threadCount);
//初始化线程数量,开启5个线程
for (int i = 0; i < 5; i++) {
int finalI = i;
ThreadUtil.execute(() -> {
try {
logger.info("线程启动,线程序列为 i = " + finalI);
//检查文件是否被处理,处理过的无需再次处理了
if (shouldProcessFile(directory)) {
//这里写你的逻辑代码
//这里写你的逻辑代码
//这里写你的逻辑代码
//这里写你的逻辑代码
}
} catch (Exception e) {
//异常处理
throw new RuntimeException(e.getMessage());
} finally {
logger.info("线程结束,线程序列为 i = " + finalI);
latch.countDown();
}
});
}
latch.await();
}
/***
* 检查文件是否被处理,处理过的无需再次处理了
**/
private static boolean shouldProcessFile(File file) {
String filePath = file.getAbsolutePath();
return processedFilesMap.putIfAbsent(filePath, true) == null;
}