java并发包之倒计数闭锁CountDownLatch

由于技术发展,并发,多线程出现,java在java5的时候引进了java.util.concurrent 包。CountDownLatch是在这个并发包下面,是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行。CountDownLatch 以一个给定的数量初始化。countDown() 每被调用一次,这一数量就减一。通过调用 await() 方法之一,线程可以阻塞等待这一数量到达零。
实例:假设一个下载软件Ant,将文件分为多个块,多个线程同时下载,只有当所有线程都下载完成之后,才可以拼接为一个完整的文件。
传统的做法是使用thread.join

public class AntJoin implements Runnable {
    private String id;
    private Long cost;
 
    public AntJoin(String id,  Long cost) {
        this.id = id;
        this.cost = cost;
    }
 
    @Override
    public void run() {
        System.out.println(id + " start:");
        try {
            Thread.sleep(cost);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(id + " end.");
    }
 
    public static void main(String[] args) throws Exception {
        System.out.println("start download...");
        Thread t1 = new Thread(new AntJoin("ANT_11111",5000L));
        Thread t2 = new Thread(new AntJoin("ANT_22222",8000L));
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("finish partition download.joint a file.");
    }
}

使用CountDownLatch实现

public class Ant implements Runnable {
    private String id;
    private CountDownLatch latch;
    private Long cost;
 
    public Ant(String id, CountDownLatch latch, Long cost) {
        this.id = id;
        this.latch = latch;
        this.cost = cost;
    }
 
    @Override
    public void run() {
        System.out.println(id + " start:");
        try {
            Thread.sleep(cost);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(id + " end.");
        latch.countDown();
    }
 
    public static void main(String[] args) {
        CountDownLatch latch=new CountDownLatch(2);
        System.out.println("start download...");
        new Thread(new Ant("ANT_11111",latch,5000L)).start();
        new Thread(new Ant("ANT_22222",latch,8000L)).start();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("finish partition download.joint a file.");
    }
}

执行结果:

start download...
ANT_11111 start:
ANT_22222 start:
ANT_11111 end.
ANT_22222 end.
finish partition download.joint a file.

以上内容都是一个大佬发给我学习的实例,我发出来做笔记希望大家一起学习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值