【线程知识点】-- CountDownLatch


CountDownLatch是什么?


CountDownLatch是在java1.5被引入的,跟它一起被引入的并发工具类还有CyclicBarrier、Semaphore、ConcurrentHashMap和BlockingQueue,它们都存在于java.util.concurrent包下。CountDownLatch这个类能够使一个线程等待其他线程完成各自的工作后再执行。例如,应用程序的主线程希望在负责启动框架服务的线程已经启动所有的框架服务之后再执行。

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





CountDownLatch如何工作


CountDownLatch.java类中定义的构造函数:


public CountDownLatch(int count) 

构造器中的计数值(count)实际上就是闭锁需要等待的线程数量。这个值只能被设置一次,而且CountDownLatch没有提供任何机制去重新设置这个计数值

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

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



简单示例

开始示例代码之前我们通过上面的了解发现CountDownLatch的作用完全可以使用join替代实现,实质作用就是让线程之间等待嘛。那么,CountDownLatch真的是画蛇添足嘛?带着这个疑问我们看下面场景:

场景一:学生写完作业之后老师开始批作业
  1. 使用join实现:

public class CountDownLatchTest {
   public static void main(String[] args) throws InterruptedException {
       People stu1 = new People("小明");
       People stu2 = new People("小红");
       People teacher = new People("张老师");
       stu1.start();
       stu2.start();
       stu1.join();
       stu2.join();
       System.out.println("学生写完作业,老师可以开始检查了~");
       teacher.start();
   }
}
class People extends Thread {
   private String name;
   public People(String name) {
       this.name = name;
   }
   @Override
   public void run()
{
       System.out.println(name + "开始了工作");
   }
}

   2. 使用CountDownLatch实现:

public class CountDownLatchTest {
   public static void main(String[] args) throws InterruptedException {
       CountDownLatch countDownLatch = new CountDownLatch(2);
       People stu1 = new People("小明",countDownLatch);
       People stu2 = new People("小红",countDownLatch);
       People teacher = new People("张老师",countDownLatch);
       stu1.start();
       stu2.start();
       countDownLatch.await();
       System.out.println("学生写完作业,老师可以开始检查了~");
       teacher.start();
   }
}
class People extends Thread {
   private String name;
   private CountDownLatch countDownLatch;
   public People(String name, CountDownLatch countDownLatch) {
       this.name = name;
       this.countDownLatch = countDownLatch;
   }
   @Override
   public void run()
{
       try {
           System.out.println(name + "开始了工作");
           Thread.sleep((long) (Math.random()*2000));
           System.out.println(name + "结束了工作");
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       countDownLatch.countDown();
   }
}

这样看来两者都可以实现这个场景。

场景二:学生写完作业之后就可以给老师看作业,学生回家

先看代码

public class CountDownLatchTest {
   public static void main(String[] args) throws InterruptedException {
       CountDownLatch countDownLatch = new CountDownLatch(2);
       People stu1 = new People("小明", countDownLatch);
       People stu2 = new People("小红", countDownLatch);
       People teacher = new People("张老师", countDownLatch);
       stu1.start();
       stu2.start();
       countDownLatch.await();
       System.out.println("学生写完作业,老师可以开始检查了~");
       teacher.start();
   }
}
class People extends Thread {
   private String name;
   private CountDownLatch countDownLatch;
   public People(String name, CountDownLatch countDownLatch) {
       this.name = name;
       this.countDownLatch = countDownLatch;
   }
   @Override
   public void run()
{
       //假设run中有两块业务逻辑,先是写作业,然后是放学回家
       try {
           System.out.println(name + "开始了工作");
           Thread.sleep((long) (Math.random() * 2000));
           System.out.println(name + "结束了工作");
           countDownLatch.countDown();
           Thread.sleep(2000);
           System.out.println(name + "放学回家玩LOL了~");
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
}

结果:

小红开始了工作
小明开始了工作
小明结束了工作
小红结束了工作
学生写完作业,老师可以开始检查了~
张老师开始了工作
张老师结束了工作
小明放学回家玩LOL了~
小红放学回家玩LOL了~
张老师放学回家玩LOL了~


总结一下两者区别:调用thread.join() 方法必须等thread 执行完毕,当前线程才能继续往下执行,而CountDownLatch通过计数器提供了更灵活的控制,只要检测到计数器为0当前线程就可以往下执行而不用管相应的thread是否执行完毕。







<think>我们首先讲解Java多线程的核心知识点,然后给出相关代码示例和解释,最后提出相关问题。Java多线程知识点详解:1.**线程的创建**:-继承Thread类,重写run方法。-实现Runnable接口,实现run方法,然后将Runnable实例作为参数传递给Thread对象。-实现Callable接口(可以返回结果或抛出异常),需要结合FutureTask使用。2.**线程的生命周期**:-新建(New)-就绪(Runnable)-运行(Running)-阻塞(Blocked)-死亡(Dead)3.**线程同步与锁**:-synchronized关键字:可以同步方法或代码块。-Lock接口及其实现类(如ReentrantLock):提供了更灵活的锁操作。4.**线程间通信**:-wait(),notify(),notifyAll()(必须在同步块或同步方法中使用,且由同步锁对象调用)-使用Condition(与Lock配合使用)的await(),signal(),signalAll()5.**线程池**:-使用Executors工厂类创建线程池(如newFixedThreadPool,newCachedThreadPool等)-使用ThreadPoolExecutor自定义线程池。6.**并发工具类**:-CountDownLatch:允许一个或多个线程等待其他线程完成操作。-CyclicBarrier:让一组线程到达一个屏障时被阻塞,直到最后一个线程到达屏障时,屏障才会开门。-Semaphore:控制同时访问特定资源的线程数量。-Exchanger:用于两个线程交换数据。7.**原子类**:-如AtomicInteger,AtomicLong等,用于实现原子操作。8.**并发集合**:-ConcurrentHashMap,CopyOnWriteArrayList,BlockingQueue等。下面我们通过代码示例来展示部分知识点。###示例1:创建线程的两种方式####方式1:继承Thread类```javapublicclassMyThreadextendsThread{@Overridepublicvoidrun(){System.out.println("线程运行中,继承Thread类");}publicstaticvoidmain(String[]args){MyThreadthread=newMyThread();thread.start();//启动线程}}```####方式2:实现Runnable接口```javapublicclassMyRunnableimplementsRunnable{@Overridepublicvoidrun(){System.out.println("线程运行中,实现Runnable接口");}publicstaticvoidmain(String[]args){Threadthread=newThread(newMyRunnable());thread.start();}}```###示例2:使用Callable和FutureTask```javaimportjava.util.concurrent.Callable;importjava.util.concurrent.FutureTask;publicclassMyCallableimplementsCallable<String>{@OverridepublicStringcall()throwsException{return"Callable返回结果";}publicstaticvoidmain(String[]args)throwsException{FutureTask<String>futureTask=newFutureTask<>(newMyCallable());Threadthread=newThread(futureTask);thread.start();System.out.println(futureTask.get());//获取返回结果}}```###示例3:使用synchronized实现同步```javapublicclassSynchronizedExample{privateintcount=0;publicsynchronizedvoidincrement(){//同步方法count++;}publicvoidincrementBlock(){synchronized(this){//同步代码块count++;}}publicstaticvoidmain(String[]args)throwsInterruptedException{SynchronizedExampleexample=newSynchronizedExample();Threadt1=newThread(()->{for(inti=0;i<1000;i++){example.increment();}});Threadt2=newThread(()->{for(inti=0;i<1000;i++){example.incrementBlock();}});t1.start();t2.start();t1.join();t2.join();System.out.println(example.count);//输出2000}}```###示例4:使用ReentrantLock```javaimportjava.util.concurrent.locks.ReentrantLock;publicclassLockExample{privateintcount=0;privateReentrantLocklock=newReentrantLock();publicvoidincrement(){lock.lock();try{count++;}finally{lock.unlock();}}publicstaticvoidmain(String[]args)throwsInterruptedException{LockExampleexample=newLockExample();Threadt1=newThread(()->{for(inti=0;i<1000;i++){example.increment();}});Threadt2=newThread(()->{for(inti=0;i<1000;i++){example.increment();}});t1.start();t2.start();t1.join();t2.join();System.out.println(example.count);//输出2000}}```###示例5:线程池的使用```javaimportjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassThreadPoolExample{publicstaticvoidmain(String[]args){ExecutorServiceexecutor=Executors.newFixedThreadPool(2);for(inti=0;i<5;i++){executor.execute(()->{System.out.println("线程"+Thread.currentThread().getName()+"执行任务");});}executor.shutdown();}}```###示例6:CountDownLatch使用```javaimportjava.util.concurrent.CountDownLatch;publicclassCountDownLatchExample{publicstaticvoidmain(String[]args)throwsInterruptedException{intworkerCount=3;CountDownLatchlatch=newCountDownLatch(workerCount);for(inti=0;i<workerCount;i++){newThread(()->{System.out.println(Thread.currentThread().getName()+"完成任务");latch.countDown();}).start();}latch.await();System.out.println("所有任务完成");}}```以上代码示例涵盖了多线程的基础和部分高级用法。接下来,我们提出一些相关问题。§§相关问题§§:1.请详细解释Java中的线程状态以及状态之间的转换。2.什么是死锁?如何避免死锁?请给出一个死锁的代码示例。3.请比较synchronized和ReentrantLock的异同点。4.线程池的参数有哪些?如何合理配置线程池参数?</think>### Java多线程知识点详解 Java多线程并发编程的核心,主要涉及线程创建、同步机制、线程通信和线程池等。以下是关键知识点及代码示例: #### 1. **线程创建** - **继承Thread类**:重写`run()`方法 - **实现Runnable接口**:更灵活(推荐) - **实现Callable接口**:可返回结果和抛异常 ```java // 方式1:继承Thread class MyThread extends Thread { @Override public void run() { System.out.println("Thread running: " + Thread.currentThread().getName()); } } // 方式2:实现Runnable class MyRunnable implements Runnable { @Override public void run() { System.out.println("Runnable running: " + Thread.currentThread().getName()); } } // 方式3:实现Callable(带返回值) import java.util.concurrent.*; class MyCallable implements Callable<String> { @Override public String call() throws Exception { return "Result from " + Thread.currentThread().getName(); } } public class Main { public static void main(String[] args) throws Exception { // 启动Thread new MyThread().start(); // 启动Runnable new Thread(new MyRunnable()).start(); // 启动Callable ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new MyCallable()); System.out.println(future.get()); // 获取返回值 executor.shutdown(); } } ``` #### 2. **线程同步** 使用`synchronized`或`Lock`解决竞态条件: ```java // 同步方法 class Counter { private int count = 0; public synchronized void increment() { count++; } } // 同步代码块 public void add() { synchronized(this) { count++; } } // 使用ReentrantLock import java.util.concurrent.locks.*; class SafeCounter { private final Lock lock = new ReentrantLock(); private int value = 0; public void increment() { lock.lock(); try { value++; } finally { lock.unlock(); } } } ``` #### 3. **线程通信** 使用`wait()`/`notify()`实现生产者-消费者模型: ```java class Buffer { private Queue<Integer> queue = new LinkedList<>(); private int capacity = 2; public synchronized void produce(int item) throws InterruptedException { while (queue.size() == capacity) { wait(); // 缓冲区满时等待 } queue.add(item); notifyAll(); // 唤醒消费者 } public synchronized int consume() throws InterruptedException { while (queue.isEmpty()) { wait(); // 缓冲区空时等待 } int item = queue.poll(); notifyAll(); // 唤醒生产者 return item; } } ``` #### 4. **线程池** 使用`ExecutorService`管理线程: ```java import java.util.concurrent.*; public class ThreadPoolDemo { public static void main(String[] args) { // 创建固定大小线程池 ExecutorService pool = Executors.newFixedThreadPool(3); // 提交任务 for (int i = 0; i < 5; i++) { pool.execute(() -> { System.out.println("Task executed by " + Thread.currentThread().getName()); }); } // 关闭线程池 pool.shutdown(); } } ``` #### 5. **并发工具类** - **CountDownLatch**:等待多个任务完成 ```java CountDownLatch latch = new CountDownLatch(3); for (int i = 0; i < 3; i++) { new Thread(() -> { // 执行任务 latch.countDown(); }).start(); } latch.await(); // 阻塞直到计数器归零 ``` - **CyclicBarrier**:线程到达屏障时等待 ```java CyclicBarrier barrier = new CyclicBarrier(3, () -> System.out.println("All threads reached barrier")); for (int i = 0; i < 3; i++) { new Thread(() -> { barrier.await(); // 等待其他线程 }).start(); } ``` #### 6. **原子操作** 使用`AtomicInteger`等原子类: ```java import java.util.concurrent.atomic.*; AtomicInteger atomicInt = new AtomicInteger(0); atomicInt.incrementAndGet(); // 原子自增 ``` #### 7. **线程状态** Java线程的6种状态: 1. **NEW**:新建未启动 2. **RUNNABLE**:可运行(包括就绪和运行中) 3. **BLOCKED**:等待监视器锁 4. **WAITING**:无限期等待(`wait()`/`join()`) 5. **TIMED_WAITING**:限期等待(`sleep()`/`wait(timeout)`) 6. **TERMINATED**:终止 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高级摸鱼工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值