多线程小程序——铠甲勇士(CountDownLatch)

public class ArmorWarrior {

   //5个铠甲召唤人

   private static final int num =5;

   //召唤器启动

    private static final CountDownLatch countDownLatch =new CountDownLatch(num);

    private static final ExecutorService executorService =Executors.newFixedThreadPool(num);

    public static void main(String[] args) throws Exception {

        executorService.submit(() ->{

            //炎龙侠核心成员,实例比较全面,六边形展示

            System.out.println("炎龙侠:炎龙铠甲,合体!");

            try {

                Thread.sleep(3000);

            } catch (InterruptedException e) {

                e.printStackTrace();

            } finally {

                countDownLatch.countDown();

                System.out.println("炎龙铠甲完成合体!");

            }

        });

        executorService.submit(() ->{

            //风鹰侠速度快,合体也快

            System.out.println("风鹰侠:风鹰铠甲,合体!");

            try {

                Thread.sleep(2000);

            } catch (InterruptedException e) {

                e.printStackTrace();

            } finally {

                countDownLatch.countDown();

                System.out.println("风鹰铠甲完成合体!");

            }

        });

        executorService.submit(() ->{

            //黑犀侠最磨叽,合体最慢

            System.out.println("黑犀侠:黑犀铠甲,合体!");

            try {

                Thread.sleep(4000);

            } catch (InterruptedException e) {

                e.printStackTrace();

            } finally {

                countDownLatch.countDown();

                System.out.println("黑犀铠甲完成合体!");

            }

        });

        //雪獒侠

        executorService.submit(() ->{

            System.out.println("雪獒侠:(还需要召唤器?!)...");

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

                e.printStackTrace();

            } finally {

                countDownLatch.countDown();

                System.out.println("雪獒铠甲完成合体!");

            }

        });

        executorService.submit(() ->{

            //地虎侠,顺带的,比炎龙慢些吧

            System.out.println("地虎侠:地虎铠甲,合体!");

            try {

                Thread.sleep(3500);

            } catch (InterruptedException e) {

                e.printStackTrace();

            } finally {

                countDownLatch.countDown();

                System.out.println("地虎铠甲完成合体!");

            }

        });

        System.out.println("等待所有铠甲召唤人,完成合体...");

        countDownLatch.await();

        System.out.println("光影铠甲,出击!");

        executorService.shutdown();

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容