【java笔记】java中的CountDownLatch线程同步工具

本文摘自简书用户“码农历险记”的文章

CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程执行完后再执行。

1. CountDownLatch原理

CountDownLatch是通过一个计数器来实现的,计数器的初始化值为线程的数量。每当一个线程完成了自己的任务后,计数器的值就相应得减1。当计数器到达0时,表示所有的线程都已完成任务,然后在闭锁上等待的线程就可以恢复执行任务。

2. 使用步骤

  • Main thread start
  • Create CountDownLatch for N threads
  • Create and start N threads
  • Main thead wait on latch
  • N threads completes there tasks are returns
  • Main thread resume execution

3. CountDownLatch的构造函数

//用等待的线程数量来进行初始化
public void CountDownLatch(int count){...}

计数器count是闭锁需要等待的线程数量,只能被设置一次,且CountDownLatch没有提供任何机制去重新设置计数器count。

与CountDownLatch的第一次交互是主线程等待其他线程。主线程必须在启动其他线程后立即调用CountDownLatch.await()方法。这样主线程的操作就会在这个方法上阻塞,直到其他线程完成各自的任务。

其他N个线程必须引用CountDownLatch闭锁对象,因为它们需要通知CountDownLatch对象,它们各自完成了任务;这种通知机制是通过CountDownLatch.countDown()方法来完成的;每调用一次,count的值就减1,因此当N个线程都调用这个方法,count的值就等于0,然后主线程就可以通过await()方法,恢复执行自己的任务。

4. 实例

MyRunable类:

package ecnu.cn;

import java.util.concurrent.CountDownLatch;

public class MyRunable implements Runnable {
    CountDownLatch latch;

    public MyRunable(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + "执行。");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            latch.countDown();
        }
    }
}

MyLatch类:

package ecnu.cn;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class MyLatch {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Main方法开始执行。");

        // 有3个线程
        int threadNum = 3;

        CountDownLatch latch = new CountDownLatch(threadNum);
        Executor executor = Executors.newFixedThreadPool(threadNum);

        List<MyRunable> myRunables = new ArrayList<MyRunable>();
        myRunables.add(new MyRunable(latch));
        myRunables.add(new MyRunable(latch));
        myRunables.add(new MyRunable(latch));

        for (MyRunable myRunable : myRunables) {
            executor.execute(myRunable);
        }

        latch.await();
        System.out.println("Main方法执行结束。");
    }
}

运行结果:

Main方法开始执行。
pool-1-thread-2执行。
pool-1-thread-3执行。
pool-1-thread-1执行。
Main方法执行结束。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值