CountDownLatch 多线程通信

来源:互联网 发布:淘宝密码格式 编辑:程序博客网 时间:2024/06/04 18:39

public void testCountDownLatch() {
        ThreadFactory factory = new ThreadFactory() {
            int i = 1;

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "线程" + i++);
            }
        };

        int size = 10;
        final CountDownLatch latch = new CountDownLatch(size);
        ExecutorService executor = Executors.newCachedThreadPool(factory);
        for (int i = 0; i < size; i++) {
            executor.submit(
                    new Runnable() {
                        @Override
                        public void run() {
                            System.out.println(Thread.currentThread().getName() + "等待执行");

                            try {
                                int time = new Random().nextInt(5);
                                TimeUnit.SECONDS.sleep(time);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            latch.countDown();
                            System.out.println(Thread.currentThread().getName() + "执行完毕");

                        }
                    }
            );
        }
        executor.shutdown();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("所有线程执行完毕");

    }

 

0 0
原创粉丝点击