普通的代码执行都是一行一行往下进行执行,如果需要同时开始异步任务,则需要以下配置,可以参考以下代码。
步骤一:
代码上添加@Async注解,方法添加返回值CompletableFuture
public class AsyncTask{
@Async
public CompletableFuture doTaskOne() throws InterruptedException {
log.info("开始执行任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务一,耗时:"+(end - start )+"毫秒");
return CompletableFuture.completedFuture("任务一完成");
}
}
步骤二:在任务调用的时候添加下面这一行代码,保证代码执行完成。
- 通过CompletableFuture.allOf(task1, task2, task3).join()实现三个异步任务都结束之前的阻塞效果
@Test
void testAsyncTask() throws InterruptedException {
long start = System.currentTimeMillis();
CompletableFuture task1 = asyncTask.doTaskOne();
CompletableFuture task2 = asyncTask.doTaskTwo();
CompletableFuture task3 = asyncTask.doTaskThree();
CompletableFuture.allOf(task1,task2,task3).join();
long end = System.currentTimeMillis();
log.info("任务全部完成,总耗时:"+(end - start)+"毫秒");
}



