zoukankan      html  css  js  c++  java
  • CountDownLatch 介绍

    package com.karl.example;
    
    import java.util.concurrent.CountDownLatch;
    
    /**
     * Created by karl.
     */
    public class CountDownLatchExample {
        public static class Task implements Runnable{
            private String name;
            private CountDownLatch latch;
            private Long timeToStart;
    
            public Task(String name, Long timeToStart, CountDownLatch latch){
                this.name = name;
                this.latch = latch;
                this.timeToStart = timeToStart;
            }
    
            @Override
            public void run() {
                try {
                    Thread.sleep(timeToStart);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println( name + " is Up");
                latch.countDown(); //计数器减1
    
            }
        }
    
        public static void main(String[] args) {
            CountDownLatch latch = new CountDownLatch(3);
            Thread t1 = new Thread(new Task("Thread 1",1000L,latch));
            Thread t2 = new Thread(new Task("Thread 2",1000L,latch));
            Thread t3 = new Thread(new Task("Thread 3",1000L,latch));
            Thread t4 = new Thread(new Task("Thread 4",1000L,latch));
            Thread t5 = new Thread(new Task("Thread 5",1000L,latch));
            Thread t6 = new Thread(new Task("Thread 6",1000L,latch));
            t1.start();
            t2.start();
            t3.start();
            t4.start();
            t5.start();
            t6.start();
            try {
                latch.await();
                System.out.println("at least 3 thread startup,application is starting now");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    结果:

    Thread 2 is Up
    Thread 1 is Up
    Thread 3 is Up
    Thread 4 is Up
    at least 3 thread startup,application is starting now
    Thread 5 is Up
    Thread 6 is Up
  • 相关阅读:
    I2S波形解析
    F407整点原子I2C波形解码
    WAVE格式文件说明
    ADC结构体初始化成员
    这次,我是真的想吐槽MDK
    I2S源程序(正点原子F407探索者)
    强制类型转换
    嵌套结构体的初始化
    lua 元方法 __index
    lua pairs 与 ipairs
  • 原文地址:https://www.cnblogs.com/zhonghan/p/5009902.html
Copyright © 2011-2022 走看看