当前位置: 移动技术网 > IT编程>开发语言>Java > Java并发编程Callable与Future的应用实例代码

Java并发编程Callable与Future的应用实例代码

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文主要探究的是java并发编程callable与future的使用,分享了相关实例代码,具体介绍如下。

我们都知道实现多线程有2种方式,一种是继承thread,一种是实现runnable,但这2种方式都有一个缺陷,在任务完成后无法获取返回结果。要想获得返回结果,就得使用callable,callable任务可以有返回值,但是没法直接从callable任务里获取返回值;想要获取callabel任务的返回值,需要用到future。所以callable任务和future模式,通常结合起来使用。

试想一个场景:需要一个帖子列表接口,除了需要返回帖子列表之外,还需要返回每条帖子的点赞列表和评论列表。一页10条帖子来计算,这个接口需要访问21次数据库,访问一次数据库按100ms计算,21次,累计时间为2.1s。这个响应时间,怕是无法令人满意的。怎么办呢?异步化改造接口。

查出帖子列表后,迭代帖子列表,在循环里起10个线程,并发去获取每条帖子的点赞列表,同时另起10个线程,并发去获取每条帖子的评论列表。这样改造之后,接口的响应时间大大缩短,在200ms。这个时候就要用callabel结合future来实现。

private list<postresponse> createpostresponselist(page<postresponse> page,final string userid){ 
    if(page.getcount()==0||page==null||page.getlist()==null){ 
      return null; 
    } 
    //获取帖子列表 
    list<postresponse> circleresponselist = page.getlist(); 
    int size=circleresponselist.size(); 
    executorservice commentpool = executors.newfixedthreadpool(size); 
    executorservice supportpool = executors.newfixedthreadpool(size); 
    try { 
      list<future> commentfuturelist = new arraylist<future>(size); 
      if (circleresponselist != null && circleresponselist.size() > 0) { 
        for (postresponse postresponse : circleresponselist) { 
          final string circleid=postresponse.getid(); 
          final string postuserid=postresponse.getuserid(); 
          //查评论列表 
          callable<list<circlereviews>> callablecomment = new callable<list<circlereviews>>() { 
            @override 
            public list<circlereviews> call() throws exception { 
              return circlereviewsbiz.getpostcomments(circleid); 
            } 
          }; 
          future f = commentpool.submit(callablecomment); 
          commentfuturelist.add(f); 
          //查点赞列表 
          callable<list<circlezan>> callablesupport = new callable<list<circlezan>>() { 
            @override 
            public list<circlezan> call() throws exception { 
              return circlezanbiz.findlist(circleid); 
            } 
          }; 
          future supportfuture = supportpool.submit(callablesupport); 
          commentfuturelist.add(supportfuture); 
        } 
 
      } 
      // 获取所有并发任务的执行结果 
      int i = 0; 
      postresponse temp = null; 
      for (future f : commentfuturelist) { 
        temp = circleresponselist.get(i); 
        temp.setcommentlist((list<circlereviews>) f.get(); 
        temp.setsupportlist((list<circlezan>) f.get(); 
        circleresponselist.set(i, temp); 
        i++; 
      } 
 
    } catch (exception e) { 
      e.printstacktrace(); 
    } finally { 
      // 关闭线程池 
      commentpool.shutdown(); 
      supportpool.shutdown(); 
    } 
    return circleresponselist; 
} 

总结

以上就是本文关于java并发编程callable与future的应用实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网