Home > Java > javaTutorial > How to use multithreading in Java to prevent the main thread from ending prematurely?

How to use multithreading in Java to prevent the main thread from ending prematurely?

PHPz
Release: 2023-04-27 16:40:15
forward
1177 people have browsed it

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) {};
Copy after login

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() {};
Copy after login

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();
    }
}
Copy after login

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();
        }
 
    }
}
Copy after login

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();
    }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template