CountDownLatch\FutureTask使用小记

等待线程执行完成小demo

第一种方式:CountDownLatch

 public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService =  Executors.newFixedThreadPool(2);
        long start = System.currentTimeMillis();

        final CountDownLatch countDownLatch = new CountDownLatch(2);
        executorService.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("down1");
                countDownLatch.countDown();
            }
            
        });

        executorService.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("down2");
                countDownLatch.countDown();
            }
            
        });
       
        try {
            countDownLatch.await();
        }catch (Exception e){
            System.out.println(11111111);
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时" + (end - start));
        // 记得要 关闭线程池
        executorService.shutdown();

    }

第二种方式:FutureTask

private final static ExecutorService executorService =  Executors.newFixedThreadPool(2);
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        Future<?> down1 = executorService.submit((Callable<Object>) () -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("down1");
            }
            return 1;
        });

        Future<?> down2 = executorService.submit((Callable<Object>) () -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("down2");
            }
            return 2;
        });
        System.out.println(down1.get());
        System.out.println(down2.get());
        long end = System.currentTimeMillis();
        System.out.println("耗时" + (end - start));

        executorService.shutdown();

    }

猜你喜欢

转载自blog.csdn.net/H_Rhui/article/details/108072024