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());
}

执行结果如下

SpringBoot 线程池监听线程执行结果

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
247
粉丝
18
喜欢
217
收藏
62
排名:731
访问:9753
私信
所有博文
社区赞助商