zoukankan      html  css  js  c++  java
  • CountDownLatch类实现同步

    首先我们看一个普通的多线程代码

    class MyThread implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "执行");
        }
    }
    
    public class TestCountDownLatch {
        public static void main(String[] args) throws InterruptedException {
            MyThread my = new MyThread();
            new Thread(my).start();
            new Thread(my).start();
            System.out.println("线程执行完毕");
        }

    在执行main方法后,输出如下,这是随机的,每次可能不同。也就是说,我们最后想输出的“线程执行完毕”没有最后执行,这并不是我们的本意,所以,这里我们想到CountDownLatch类,对上面的代码稍作修改

    修改后代码:

    class MyThread implements Runnable {
        private CountDownLatch latch;
    
        public MyThread(CountDownLatch latch) {
            this.latch = latch;
        }
    
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "执行");
            latch.countDown();
        }
    }
    
    public class TestCountDownLatch {
        public static void main(String[] args) throws InterruptedException {
            CountDownLatch latch = new CountDownLatch(2);
            MyThread my = new MyThread(latch);
            new Thread(my).start();
            new Thread(my).start();
            latch.await();
            System.out.println("线程执行完毕");
        }
    CountDownLatch latch = new CountDownLatch(2);数值2,代表这里申明2个线程
    latch.await();await方法为等待,等待上面执行完成后才会执行下面的代码

    latch.countDown();countDown方法为减减操作

    我们再次执行如下:

    我们发现,不管执行多少次,“线程执行完毕”都是最后执行,这就实现了多线程的同步操作。

  • 相关阅读:
    及时说爱
    坚持
    html5新增元素
    js call
    smarty实例教程
    JS 跨浏览器兼容问题
    CSS3中的5个有趣的新技术
    jQuery和dom转化
    前端安全问题
    js apply
  • 原文地址:https://www.cnblogs.com/feiyangbahu/p/9719924.html
Copyright © 2011-2022 走看看