run() { try { FileCleanTaskResponse poll = pollTasks(1); List<FileCleanTask> tasks = poll.getCleanTasks(); log.info("cleantasks:" + tasks); if (tasks.isEmpty()) { try { Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } } long startTimeMills = System.currentTimeMillis(); List<Future> futures = new ArrayList<>(); for (FileCleanTask task : tasks) { List<String> dirs = task.getCleanDirs(); log.info("cleandirs:" + dirs); dirs.stream().forEach(dir -> { Future future = executor.submit(new FileCleanRunnable(dir)); futures.add(future); }); } //等待所有线程执行结束 for (Future future : futures) { try { future.get(); } catch (InterruptedException e) { log.error("clean task interupt", e); } catch (ExecutionException e) { log.error("clean task ", e); } } log.info("ALL File clean thread finish,cost: {} ms", (System.currentTimeMillis() - startTimeMills)); }添加异常并且可以过kw
时间: 2024-02-10 22:14:36 浏览: 58
您可以将代码修改为以下形式,添加了异常处理,并且去掉了最后一行的 "添加异常并且可以过kw":
```
run() {
try {
FileCleanTaskResponse poll = pollTasks(1);
List<FileCleanTask> tasks = poll.getCleanTasks();
log.info("cleantasks:" + tasks);
if (tasks.isEmpty()) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
log.error("Interrupted while sleeping", e);
}
}
long startTimeMills = System.currentTimeMillis();
List<Future> futures = new ArrayList<>();
for (FileCleanTask task : tasks) {
List<String> dirs = task.getCleanDirs();
log.info("cleandirs:" + dirs);
dirs.stream().forEach(dir -> {
Future future = executor.submit(new FileCleanRunnable(dir));
futures.add(future);
});
}
//等待所有线程执行结束
for (Future future : futures) {
try {
future.get();
} catch (InterruptedException e) {
log.error("Interrupted while waiting for thread to finish", e);
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
log.error("Error executing thread", e);
}
}
log.info("ALL File clean thread finish,cost: {} ms", (System.currentTimeMillis() - startTimeMills));
} catch (Exception e) {
log.error("An error occurred while running the task", e);
}
}
```
这样做的好处是,如果在执行任务的过程中遇到异常,程序不会立即退出,而是记录下错误信息,然后继续执行后面的任务。同时,如果在等待线程执行结束的过程中程序被中断,也会记录下错误信息,并保证程序正确退出。
阅读全文