美文网首页
countdown设计模式

countdown设计模式

作者: jiahzhon | 来源:发表于2020-10-13 17:03 被阅读0次
    • 使用JDK自带的countdownLatch
    public class JDKCountDown {
    
        private static final Random random = new Random(System.currentTimeMillis());
    
        public static void main(String[] args) throws InterruptedException {
    
            final CountDownLatch latch = new CountDownLatch(5);
            System.out.println("准备多线程处理任务.");
            //The first phase.
    
            IntStream.rangeClosed(1, 5).forEach(i ->
                    new Thread(() -> {
                        System.out.println(Thread.currentThread().getName() + " is working.");
                        try {
                            Thread.sleep(random.nextInt(1000));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        latch.countDown();
                    }, String.valueOf(i)).start()
            );
    
            latch.await();
            //The second phase.
            System.out.println("多线程任务全部结束,准备第二阶段任务");
            System.out.println("............");
            System.out.println("FINISH");
    
        }
    }
    

    相关文章

      网友评论

          本文标题:countdown设计模式

          本文链接:https://www.haomeiwen.com/subject/bryxpktx.html