CountDownLatch是Java中一个同步工具类,可以用于控制线程的等待,它可以让某一个线程等待直到倒计时结束,再开始执行。
JAVA 多线程编程之CountDownLatch使用详解
什么是CountDownLatch
CountDownLatch是Java中一个同步工具类,可以用于控制线程的等待,它可以让某一个线程等待直到倒计时结束,再开始执行。
CountDownLatch的构造方法
public CountDownLatch(int count) { }
count表示倒计时数量
CountDownLatch的主要方法
public void countDown() //计数器减1
public void await() throws InterruptedException //等待所有计数器归零
public boolean await(long timeout, TimeUnit unit) throws InterruptedException //等待一定时间,如果到了指定的时间,计数器还没有归零,则返回false,否则返回true
CountDownLatch的示例
示例一:等待其他线程执行完毕再开始执行
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(2);
Thread thread1 = new Thread(() -> {
System.out.println("Thread1 is running!");
countDownLatch.countDown();
});
Thread thread2 = new Thread(() -> {
System.out.println("Thread2 is running!");
countDownLatch.countDown();
});
thread1.start();
thread2.start();
countDownLatch.await();
System.out.println("All threads have finished running!");
}
}
上述示例中,创建了一个CountDownLatch对象,计数器数值为2,即需要等待两个线程执行完毕后才能继续执行主线程。在两个子线程执行完任务后,分别调用countDown()方法以减少计数器的值,主线程再调用await()方法等待计数器的值为0时继续执行。
示例二:等待其他线程执行完毕并执行其他任务
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(2);
Thread thread1 = new Thread(() -> {
System.out.println("Thread1 is running!");
countDownLatch.countDown();
});
Thread thread2 = new Thread(() -> {
System.out.println("Thread2 is running!");
countDownLatch.countDown();
});
thread1.start();
thread2.start();
countDownLatch.await();
System.out.println("All threads have finished running!");
// 等待其他任务执行完毕
System.out.println("Doing some other work...");
}
}
上述示例中,与示例一类似,等待两个线程执行完毕后继续执行主线程。但在主线程执行完“All threads have finished running!”后,还可以继续执行其他任务,例如输出“Doing some other work...”
总结
CountDownLatch可以用于线程间的协作,控制线程的执行顺序,让一个或一组线程等待另外一组线程执行完后才执行。通过控制计数器的值,可以实现多个线程的同步执行。
本文标题为:JAVA 多线程编程之CountDownLatch使用详解
基础教程推荐
- SpringBoot实现在webapp下直接访问html,jsp 2023-06-30
- 详解Java如何实现自定义注解 2023-01-24
- Spring笔记-@Order注解和Ordered接口解析 2023-04-17
- SpringBoot项目打包war包时无法运行问题的解决方式 2023-01-09
- spring缓存代码详解 2024-01-07
- 减少代码开发工作的Java库lombok及注解的使用学习 2023-03-06
- 使用JS显示倒计时数字时钟效果 2023-08-02
- java+io+swing实现学生信息管理系统 2023-03-15
- Java分布式服务框架Dubbo介绍 2023-02-10
- SMBMS超市订单管理系统的网站源码 2024-01-03
