首页 > 编程语言 > 详细

线程池调用案例

时间:2018-09-17 17:01:01      阅读:152      评论:0      收藏:0      [点我收藏+]
Runnable:
    @Test
    public void testFixedThreadPool() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            final int index = i;
            fixedThreadPool.execute(() -> {
                try {
                    log.info("newFixedThreadPool,index:{}", index);
                } catch (Exception e) {
                    log.info("newFixedThreadPool,index:{},ErrorMsg:{}", index, e.getMessage());
                }
            });
        }
        fixedThreadPool.shutdown();
        while(true){
            if(fixedThreadPool.isTerminated()){
                log.info("endd");
                break;
            }
        }
        log.info("end");
    }
Callable:
  @Test
    public void testCallable() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        List<Future<String>> resultList = Lists.newArrayList();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            Future<String> future = fixedThreadPool.submit(() -> {
                try {
                    Thread.sleep(2000);
                    log.info("newFixedThreadPool,index:{}", index);
                } catch (Exception e) {
                    log.info("newFixedThreadPool,index:{},ErrorMsg:{}", index, e.getMessage());
                }
                return "success";
            });
            resultList.add(future);
        }
        resultList.forEach(x -> {
            try {
                log.info("result:{}", x.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                fixedThreadPool.shutdownNow();
                e.printStackTrace();
                return;
            }
        });
        log.info("end");
    }
参考:

https://blog.csdn.net/qq_31441667/article/details/78830395

https://blog.csdn.net/lisheng19870305/article/details/44747741

https://mp.weixin.qq.com/s/GvJvDtMYERHSTVWQaY9BEg

线程池调用案例

原文:https://www.cnblogs.com/hongdada/p/9662868.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!