码迷,mamicode.com
首页 > 其他好文 > 详细

CountDownLatch 介绍

时间:2015-12-01 14:28:56      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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

 

CountDownLatch 介绍

标签:

原文地址:http://www.cnblogs.com/zhonghan/p/5009902.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!