【Java】并行执行任务

如果你不相信努力和时光,那么成果就会是第一个选择辜负你的。不要去否定你自己的过去,也不要用你的过去牵扯你现在的努力和对未来的展望。不是因为拥有希望你才去努力,而是去努力了,你才有可能看到希望的光芒。【Java】并行执行任务,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

在实际的应用上,我们平时需要调用第三方的接口,可能会调用多个接口,串行执行的话,
就需要等待所有的接口调用完成之后才获取到结果,那我们有没有并行的方法的呢?

串行执行

以下是三个接口,假设他们额的执行耗时,分别为1S,2S和3S ,串行执行的话,需要等待6S才可得到返回的结果。

    public static void intf() {
            // 模拟执行耗时
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("接口1");
        }

public static void intf2() {
            // 模拟执行耗时
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("接口2");
        }

public static void intf3() {
            // 模拟执行耗时
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("接口3");
        }




public static void main(String[] args) {
            long startTime = System.currentTimeMillis();
            intf();
            intf2();
            intf3();
            long endTime = System.currentTimeMillis();
            System.out.println("代码段执行时间:" + (endTime - startTime) + "ms");
        }

执行耗时

接口1
接口2
接口3
代码段执行时间:6048ms

并行执行

CountDownLatch

 public static void getIntfResult() {
        ExecutorService executorService = Executors.newCachedThreadPool();
        CountDownLatch latch = new CountDownLatch(3);

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                intf();
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                intf2();
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                intf3();
                latch.countDown();
            }
        });
        try {
            // 一定记得加上timeout时间,防止阻塞主线程
            latch.await(3000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //4.等待所有子任务完成,组装活动标签信息

        //5.关闭线程池
        executorService.shutdown();
    }

执行耗时

接口1
接口2
接口3
代码段执行时间:3009ms

ExecutorService.invokeAll

  public static void getIntfResultByInvokeAll(){
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Callable<String>> tasks = new ArrayList();
        tasks.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                intf();
                return null;
            }
        });
        tasks.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                intf2();
                return null;
            }
        });
        tasks.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                intf3();
                return null;
            }
        });
        try {
            List<Future<String>> futureList = executorService.invokeAll(tasks, 3000, TimeUnit.MILLISECONDS);
            for (Future<String> future : futureList) {
                // 获取线程执行结果
                try {
                    String activityTag = future.get();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //关闭线程池
        executorService.shutdown();
    }

执行耗时

接口1
接口2
接口3
代码段执行时间:3020ms

CompletableFuture

    public static void getIntfResultByFuture() {
        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> intf());
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> intf2());
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> intf3());
        try {
            //获取并行执行任务结果
            System.out.println(future3.get());
            System.out.println(future1.get());
            System.out.println(future2.get());
        } catch (Exception e) {

        }
    }

执行耗时

接口1
接口2
接口3
代码段执行时间:3154ms

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/197518.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!