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。 (编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|