SpringBoot 线程池监听线程执行结果
前言
用了 @Async 这个注解的方法,称之为异步方法,这些方法在执行时,会在独立线程中执行,调用者无需等待它的完成,便可继续其他的操作,但是调用者如何知道它执行完了。
监听执行结果
返回值封装类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
private Integer code;
private String msg;
}
@Async
@Override
public Future<Result> syncFileWithResult() {
log.info("sync file task {} is start",Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("sync file task is done");
return new AsyncResult<>(new Result(0,"success"));
}
测试
@Test
public void threadPoolWithResultTest() throws InterruptedException, ExecutionException {
Future<Result> result = threadPoolService.syncFileWithResult();
// 循环检测
while (!result.isDone()) {
// 避免检测过于频繁
Thread.sleep(500);
// 避免重复打印
if (!result.isDone()) {
log.info("sync file task is doing");
}
}
log.info("result {}",result.get().toString());
}
执行结果如下
本作品采用《CC 协议》,转载必须注明作者和本文链接