• 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
  • 相关阅读:
    psy & vr
    psy 2
    psy
    linux c中select使用技巧
    hostent h_addr_list
    gethostbyname() -- 用域名或主机名获取IP地址
    c_select 调用参数说明
    [NYOJ 737] 石子合并(一)
    [HDU 1059] Dividing
    [HDU 1789] Doing Homework again
  • 原文地址:https://www.cnblogs.com/zhonghan/p/5009902.html
Copyright © 2020-2023  润新知