【Java】串行、并行执行任务

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

串行执行

以下是三个接口,假设他们额的执行耗时,分别为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

你可能感兴趣的:(java,java,算法,开发语言)