当前位置: 首页 > news >正文

JAVA 多线程入门例子:CountDownLatch

  • 首先确定线程数量。如果数据集合的大小小于50,就只使用一个线程;否则使用5个线程。
  • 计算每个线程平均处理的数据数量sizePerThread以及余数remainder
  • 在划分数据子集合时,对于每个线程的处理范围进行计算。如果有余数,就将余数依次分配到前面的线程中(这里是简单地让前面的线程多处理一个数据)。
  • 最后一个线程的结束索引直接设置为数据集合的大小,确保能处理完所有数据。
  • 每个线程在处理完自己的数据后,调用latch.countDown(),主线程通过latch.await()等待所有线程完成任务后,再继续执行后续操作。
  • CopyOnWriteArrayList,它是线程安全的,适用于读多写少的场景
package com.syplatform;import static org.junit.Assert.assertTrue;import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;import org.junit.Test;/*** Unit test for simple App.*/
public class AppTest {/*** Rigorous Test :-)*/@Testpublic void shouldAnswerWithTrue() throws InterruptedException {CopyOnWriteArrayList<Integer> finalList = new CopyOnWriteArrayList<>();List<Integer> dataList = new ArrayList<>();for (int i = 1; i <= 101; i++) {dataList.add(i);}// 根据数据量决定线程数量int numThreads = dataList.size() < 50 ? 1 : 5;int size = dataList.size();int partSize = size / numThreads;// 处理不能整除的情况,将剩余的任务分配到前面的线程中int remainder = size % numThreads;int startIndex = 0;CountDownLatch latch = new CountDownLatch(numThreads);for (int i = 0; i < numThreads; i++) {int endIndex = startIndex + partSize + (i < remainder ? 1 : 0);List<Integer> subList = dataList.subList(startIndex, endIndex);startIndex = endIndex;Thread thread = new Thread(() -> {for (Integer num : subList) {finalList.add(num);System.out.println(Thread.currentThread().getName() + " processing " + num);}latch.countDown();});thread.start();}latch.await();System.out.println("All threads have finished processing.");assertTrue(finalList.size() == 101);}
}

http://www.lryc.cn/news/457983.html

相关文章:

  • k8s jenkins 动态创建slave
  • MVS海康工业相机达不到标称最大帧率
  • 数据结构:用双栈实现一个队列
  • QScroller Class
  • React高阶组件详解
  • TextView把其它控件挤出屏幕的处理办法
  • 长度为 K 的重复字符子串数目
  • html+css+js实现轮播图
  • Boost集成模型异同
  • 【系统架构设计师】案例专题四:嵌入式系统考点梳理
  • Ngin入门套餐
  • 使用linux编译main.cpp文件
  • 服务器部署‌Traefik 实现子级域名路由服务(对外子域名80,路由对内大端口)
  • @RequestParam @PathVirable @RequestBody @ApiParam的区别
  • Vulnhub靶场案例渗透[5]- DC4
  • http协议概述与状态码
  • Golang 进阶5—— 反射
  • react 封装防抖
  • Java项目-----图形验证码登陆实现
  • 【网络代理模块】反向代理(上)
  • 2-112基于matlab的协同干扰功率分配模型
  • 数据结构之——二叉树
  • 多层感知机(MLP)实现考勤预测二分类任务(sklearn)
  • 文件与目录的基本操作
  • Python入门笔记(三)
  • PostgreSQL 任意命令执行漏洞(CVE-2019-9193)
  • 使用tgz包下载安装clickhouse低版本
  • 外包功能测试干了6个月,技术退步太明显了。。。。。
  • 动态规划和贪心算法
  • python爬虫--tx动漫完整信息抓取