zoukankan      html  css  js  c++  java
  • CountDownLatch的使用

    通俗的讲就是,CountDownLatch相当于一扇大门,在大门打开之前所有线程都被阻断,一旦大门打开所有线程都将通过,但是一旦大门打开,所有线程都通过了,那么这个CountDownLatch的状态就失效了,门的状态也就不能变了,只能是打开状态。也就是说CountDownLatch的状态是一次性的

    public class CountDownLatchDemo {
        
        final static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    
        public static void main(String[] args) throws InterruptedException {
            CountDownLatch latch = new CountDownLatch(2);// 两个工人的协作
            Worker worker1 = new Worker("zhangsan", 5000, latch);
            Worker worker2 = new Worker("lisi", 8000, latch);
            worker1.start();//
            worker2.start();//
            latch.await();// 等待所有工人完成工作
            System.out.println("all work done at " + sdf.format(new Date()));
        }
    
        static class Worker extends Thread {
            String workerName;
            int workTime;
            CountDownLatch latch;
    
            public Worker(String workerName, int workTime, CountDownLatch latch) {
                this.workerName = workerName;
                this.workTime = workTime;
                this.latch = latch;
            }
    
            public void run() {
                System.out.println(workerName + " start at " + sdf.format(new Date()));
                doWork();// 工作了
                System.out.println( workerName + " complete at " + sdf.format(new Date()));
                latch.countDown();// 工人完成工作,计数器减一
    
            }
    
            private void doWork() {
                try {
                    Thread.sleep(workTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 相关阅读:
    Nodejs服务器搭建
    CRC8校验,生成多项式:X8 + X2 + X + 1
    windows server 2019添加开机启动项
    Ubuntu20.04下SSH2安装, gulp live报错解决
    Ubuntu 20.04 开机执行自定义脚本
    STUN/TURN服务器搭建
    PostgreSQL开启远程连接
    Ubuntu 20.04 开机执行自定义脚本
    CentOS下 rpm软件包的安装与卸载
    Ubuntu18.04安装JDK1.8.0_11
  • 原文地址:https://www.cnblogs.com/moris5013/p/10905693.html
Copyright © 2011-2022 走看看