


CountDownLatch
CountDownLatch
(also called a lock) is a synchronization helper class that allows one or more threads to wait until other threads complete a set of operations.CountDownLatch
Initialized with the given count value. The await method will block until the current count value (count). Since the call to the countDown method reaches 0, all waiting threads will be released after the count is 0, and subsequent calls to the await method will return immediately.
Construction method:
//参数count为计数值 public CountDownLatch(int count) {};
Common methods
// 调用 await() 方法的线程会被挂起,它会等待直到 count 值为 0 才继续执行 public void await() throws InterruptedException {}; // 和 await() 类似,若等待 timeout 时长后,count 值还是没有变为 0,不再等待,继续执行 public boolean await(long timeout, TimeUnit unit) throws InterruptedException {}; // 会将 count 减 1,直至为 0 public void countDown() {};
Use cases
The first is to create an instance CountDownLatch countDown = new CountDownLatch(2);
After the thread that needs to be synchronized is executed, the count is -1, countDown.countDown();
For threads that need to wait for other threads to finish executing before running, call countDown.await() to achieve blocking synchronization.
as follows.
Application Scenario
CountDownLatch is generally used as a countdown counter for multi-threads, forcing them to wait for the completion of the execution of another set of tasks (initialization decision of CountDownLatch).
Two usage scenarios of CountDownLatch:
Let multiple threads wait and simulate concurrency.
Let a single thread wait, and after multiple threads (tasks) are completed, summarize and merge.
Scenario 1: Simulate concurrency
import java.util.concurrent.CountDownLatch; /** * 让多个线程等待:模拟并发,让并发线程一起执行 */ public class CountDownLatchTest { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(1); for (int i = 0; i < 5; i++) { new Thread(() -> { try { // 等待 countDownLatch.await(); String parter = "【" + Thread.currentThread().getName() + "】"; System.out.println(parter + "开始执行……"); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } Thread.sleep(2000); countDownLatch.countDown(); } }
Scenario 2: After multiple threads are completed, summarize and merge
Many times, our concurrent tasks, There are before and after dependencies; for example, the data details page needs to call multiple interfaces at the same time to obtain data. After concurrent requests obtain the data, the results need to be merged; or after multiple data operations are completed, data check is required; this is actually: in multiple After the thread (task) is completed, the scenario is summarized and merged.
import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; /** * 让单个线程等待:多个线程(任务)完成后,进行汇总合并 */ public class CountDownLatchTest3 { //用于聚合所有的统计指标 private static Map map = new ConcurrentHashMap(); //创建计数器,这里需要统计4个指标 private static CountDownLatch countDownLatch = new CountDownLatch(4); public static void main(String[] args) throws Exception { //记录开始时间 long startTime = System.currentTimeMillis(); Thread countUserThread = new Thread(() -> { try { System.out.println("正在统计新增用户数量"); Thread.sleep(3000);//任务执行需要3秒 map.put("userNumber", 100);//保存结果值 System.out.println("统计新增用户数量完毕"); countDownLatch.countDown();//标记已经完成一个任务 } catch (InterruptedException e) { e.printStackTrace(); } }); Thread countOrderThread = new Thread(() -> { try { System.out.println("正在统计订单数量"); Thread.sleep(3000);//任务执行需要3秒 map.put("countOrder", 20);//保存结果值 System.out.println("统计订单数量完毕"); countDownLatch.countDown();//标记已经完成一个任务 } catch (InterruptedException e) { e.printStackTrace(); } }); Thread countGoodsThread = new Thread(() -> { try { System.out.println("正在商品销量"); Thread.sleep(3000);//任务执行需要3秒 map.put("countGoods", 300);//保存结果值 System.out.println("统计商品销量完毕"); countDownLatch.countDown();//标记已经完成一个任务 } catch (InterruptedException e) { e.printStackTrace(); } }); Thread countmoneyThread = new Thread(() -> { try { System.out.println("正在总销售额"); Thread.sleep(3000);//任务执行需要3秒 map.put("countMoney", 40000);//保存结果值 System.out.println("统计销售额完毕"); countDownLatch.countDown();//标记已经完成一个任务 } catch (InterruptedException e) { e.printStackTrace(); } }); //启动子线程执行任务 countUserThread.start(); countGoodsThread.start(); countOrderThread.start(); countmoneyThread.start(); try { //主线程等待所有统计指标执行完毕 countDownLatch.await(); long endTime = System.currentTimeMillis();//记录结束时间 System.out.println("------统计指标全部完成--------"); System.out.println("统计结果为:" + map); System.out.println("任务总执行时间为" + (endTime - startTime) + "ms"); } catch (InterruptedException e) { e.printStackTrace(); } } }
Let’s get to the point
Use multi-threading instead of for loop to improve query efficiency and prevent the main thread from ending early and causing data errors in other threads
Go directly to the code:
@Override public AppResponse getLocations() throws InterruptedException { List<GetLocationVO> vos = new ArrayList<>(); vos = projectDao.getLocationOne(); // 原来的代码 // for (GetLocationVO vo : vos) { // List<LocationVO> children = projectDao.getLocationChildren(vo.getId()); // vo.setChildren(children); // } //改造后的代码 Thread(vos,10); return AppResponse.success("查询成功",vos); } //此处有加锁 public synchronized void Thread(List<GetLocationVO> list, int nThread) throws InterruptedException { if (CollectionUtils.isEmpty(list) || nThread <= 0 || CollectionUtils.isEmpty(list)) { return; } CountDownLatch latch = new CountDownLatch(list.size());//创建一个计数器(大小为当前数组的大小,确保所有执行完主线程才结束) ExecutorService pool = Executors.newFixedThreadPool(nThread);//创建一个固定的线程池 for (GetLocationVO vo : list) { pool.execute(() -> { //处理的业务 List<LocationVO> children = projectDao.getLocationChildren(vo.getId()); vo.setChildren(children); latch.countDown(); }); } latch.await(); pool.shutdown(); }
The above is the detailed content of How to use multithreading in Java to prevent the main thread from ending prematurely?. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
