• Spring Boot教程(十)异步方法测试


    测试

    测试代码如下:

    @Component
    public class AppRunner implements CommandLineRunner {
    
        private static final Logger logger = LoggerFactory.getLogger(AppRunner.class);
    
        private final GitHubLookupService gitHubLookupService;
    
        public AppRunner(GitHubLookupService gitHubLookupService) {
            this.gitHubLookupService = gitHubLookupService;
        }
    
        @Override
        public void run(String... args) throws Exception {
            // Start the clock
            long start = System.currentTimeMillis();
    
            // Kick of multiple, asynchronous lookups
            Future<User> page1 = gitHubLookupService.findUser("PivotalSoftware");
            Future<User> page2 = gitHubLookupService.findUser("CloudFoundry");
            Future<User> page3 = gitHubLookupService.findUser("Spring-Projects");
    
            // Wait until they are all done
            while (!(page1.isDone() && page2.isDone() && page3.isDone())) {
                Thread.sleep(10); //10-millisecond pause between each check
            }
    
            // Print results, including elapsed time
            logger.info("Elapsed time: " + (System.currentTimeMillis() - start));
            logger.info("--> " + page1.get());
            logger.info("--> " + page2.get());
            logger.info("--> " + page3.get());
        }
    
    }
    

    启动程序,控制台会打印:

    2017-04-30 13:11:10.351 INFO 1511 — [ GithubLookup-1] com.forezp.service.GitHubLookupService : Looking up PivotalSoftware 
    2017-04-30 13:11:10.351 INFO 1511 — [ GithubLookup-2] com.forezp.service.GitHubLookupService : Looking up CloudFoundry 
    2017-04-30 13:11:13.144 INFO 1511 — [ GithubLookup-2] com.forezp.service.GitHubLookupService : Looking up Spring-Projects
    

    耗时:3908

    分析:可以卡的前面2个方法分别在GithubLookup-1 和GithubLookup-2执行,第三个在GithubLookup-2执行,注意因为在配置线程池的时候最大线程为2.如果你把线程池的个数为3的时候,耗时减少。

    如果去掉@Async,你会发现,执行这三个方法都在main线程中执行。耗时总结,如下:

    2017-04-30 13:13:00.934 INFO 1527 — [ main] com.forezp.service.GitHubLookupService : Looking up PivotalSoftware 
    2017-04-30 13:13:03.571 INFO 1527 — [ main] com.forezp.service.GitHubLookupService : Looking up CloudFoundry 
    2017-04-30 13:13:04.865 INFO 1527 — [ main] com.forezp.service.GitHubLookupService : Looking up Spring-Projects
    

    源码来源

  • 相关阅读:
    c#: 传不确定个数参的方法
    导出Excel并设置样式
    无线网络国际会议排名
    初学Java接口
    初学Java修饰符
    [转]计算机类核心期刊投稿的一些资料汇总
    初学Java数据类型和变量
    初学Java数组
    初学Java运算符
    几个著名P2P会议与期刊及领军人物
  • 原文地址:https://www.cnblogs.com/allalongx/p/8482072.html
Copyright © 2020-2023  润新知