3. 测试编写的异步方法
- /** @author shuang.kou */
- @RestController
- @RequestMapping("/async")
- public class AsyncController {
- @Autowired
- AsyncService asyncService;
-
- @GetMapping("/movies")
- public String completableFutureTask() throws ExecutionException, InterruptedException {
- //开始时间
- long start = System.currentTimeMillis();
- // 开始执行大量的异步任务
- List<String> words = Arrays.asList("F", "T", "S", "Z", "J", "C");
- List<CompletableFuture<List<String>>> completableFutureList =
- words.stream()
- .map(word -> asyncService.completableFutureTask(word))
- .collect(Collectors.toList());
- // CompletableFuture.join()方法可以获取他们的结果并将结果连接起来
- List<List<String>> results = completableFutureList.stream().map(CompletableFuture::join).collect(Collectors.toList());
- // 打印结果以及运行程序运行花费时间
- System.out.println("Elapsed time: " + (System.currentTimeMillis() - start));
- return results.toString();
- }
- }
请求这个接口,控制台打印出下面的内容:
- 2019-10-01 13:50:17.007 WARN 18793 --- [lTaskExecutor-1] g.j.a.service.AsyncService : My ThreadPoolTaskExecutor-1start this task!
- 2019-10-01 13:50:17.007 WARN 18793 --- [lTaskExecutor-6] g.j.a.service.AsyncService : My ThreadPoolTaskExecutor-6start this task!
- 2019-10-01 13:50:17.007 WARN 18793 --- [lTaskExecutor-5] g.j.a.service.AsyncService : My ThreadPoolTaskExecutor-5start this task!
- 2019-10-01 13:50:17.007 WARN 18793 --- [lTaskExecutor-4] g.j.a.service.AsyncService : My ThreadPoolTaskExecutor-4start this task!
- 2019-10-01 13:50:17.007 WARN 18793 --- [lTaskExecutor-3] g.j.a.service.AsyncService : My ThreadPoolTaskExecutor-3start this task!
- 2019-10-01 13:50:17.007 WARN 18793 --- [lTaskExecutor-2] g.j.a.service.AsyncService : My ThreadPoolTaskExecutor-2start this task!
- Elapsed time: 1010
首先我们可以看到处理所有任务花费的时间大概是 1 s。这与我们自定义的 ThreadPoolTaskExecutor 有关,我们配置的核心线程数是 6 ,然后通过通过下面的代码模拟分配了 6 个任务给系统执行。这样每个线程都会被分配到一个任务,每个任务执行花费时间是 1 s ,所以处理 6 个任务的总花费时间是 1 s。
- List<String> words = Arrays.asList("F", "T", "S", "Z", "J", "C");
- List<CompletableFuture<List<String>>> completableFutureList =
- words.stream()
- .map(word -> asyncService.completableFutureTask(word))
- .collect(Collectors.toList());
你可以自己验证一下,试着去把核心线程数的数量改为 3 ,再次请求这个接口你会发现处理所有任务花费的时间大概是 2 s。 (编辑:衡阳站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|