CountDownLatch的学习和图解



package com.example;

import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class MyClass {

    public static void main(String args[]) {
        System.out.println("main->" + Thread.currentThread());
        final CountDownLatch latch = new CountDownLatch(1);

        System.out.println("Mission Start" + new Date().getTime());

        new Thread(new Runnable() {
            @Override
            public void run() {
                Worker worker1 = new Worker("zhang san", 2000, latch);
                Worker worker2 = new Worker("Wang er", 8000, latch);

                worker1.start();
                worker2.start();

                System.out.println("before await" + new Date().getTime());

                try {
                    //latch.await(200, TimeUnit.MILLISECONDS);//这里只要是latch 执行完了,那么这里
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.print("InterruptedException");
                }
                System.out.println("after await" + new Date().getTime());

            }
        }).start();


        System.out.println("Mission Complete" + new Date().getTime());
    }

}

class Worker extends Thread{
    CountDownLatch latch;
    int sleepTime;
    String workName;

    public Worker(String workName,int sleepTime,CountDownLatch latch){
        this.workName = workName;
        this.sleepTime = sleepTime;
        this.latch = latch;
    }
    @Override
    public void run() {

        System.out.println("worker " + workName + " start to work"+new Date().getTime());
            work();
        System.out.println("worker " + workName + " finish work"+new Date().getTime());

    }

    public void  work(){
        try{
            Thread.sleep(sleepTime);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            latch.countDown();
        }
    }
}


参考;http://www.iteye.com/topic/1002652





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值