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方法为减减操作

    我们再次执行如下:

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

  • 相关阅读:
    oracle_jdbc_insert_into
    MySQL 性能比较测试:MySQL 5.6 GA -vs- MySQL 5.5
    centos去下载mysql应该怎么选择linux版本
    centos_radhat升级系统
    phpmyadmin 配置方法
    js 判断js函数,变量是否存在
    mysqlbinlog- 处理二进制日志文件的实用工具 学习笔记
    linux基本命令
    4 MySQL程序概述(包含mysql配置文件配置原理)-学习笔记
    Python学习笔记4 高级特性_20170618
  • 原文地址:https://www.cnblogs.com/feiyangbahu/p/9719924.html
Copyright © 2011-2022 走看看