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

Kotlin协程Semaphore withPermit约束并发任务数量

Kotlin协程Semaphore withPermit约束并发任务数量

 

 

import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlockingfun main() {val permits = 1 //注意观察1,2,3时候并发跑出来的任务状况val semaphore = Semaphore(permits)runBlocking {launch {myfun("a", semaphore)}launch {myfun("b", semaphore)}launch {myfun("c", semaphore)}println("启动完毕")delay(5000)}
}private suspend fun myfun(tag: String? = null, semaphore: Semaphore) {val start = System.currentTimeMillis()println("$tag start @$start")semaphore.withPermit {withTimeout(5000) {runInterruptible {runBlocking {delay(1000)}}}}val end = System.currentTimeMillis()println("$tag end 耗时=${end - start} @$end")
}

1、当 permits = 1

启动完毕
a start @1744097960395
b start @1744097960406
c start @1744097960411
a end 耗时=1026 @1744097961421
b end 耗时=2023 @1744097962429
c end 耗时=3019 @1744097963430

 

 

 

2、当 permits = 2

启动完毕
a start @1744097988824
b start @1744097988833
c start @1744097988834
b end 耗时=1016 @1744097989849
a end 耗时=1025 @1744097989849
c end 耗时=2024 @1744097990858

 

 

3、当 permits = 3

启动完毕
a start @1744098013438
b start @1744098013450
c start @1744098013450
c end 耗时=1007 @1744098014457
b end 耗时=1007 @1744098014457
a end 耗时=1019 @1744098014457

 

简单的说,Semaphore的permits约束了同时并发的协程任务数量。当并发任务数量超过permits后,多出来的任务就要等待permits数量内的任务完成后、空出余量才能投入运行。

 

 

Kotlin协程runBlocking并发launch,Semaphore同步1个launch任务运行_kotlin launch仅运行一次-CSDN博客文章浏览阅读1.1k次。本文介绍了如何使用Kotlin的协程和Semaphore进行并发控制,确保在并发环境中A、B、C三个任务按照顺序运行,即使引入Java版Semaphore也会有不同表现。 https://blog.csdn.net/zhangphil/article/details/132356885

新Java线程Semaphore:并行环境下访问竞争资源控制_并发进程竞争资源如何进行控制-CSDN博客文章浏览阅读585次。本文介绍Java 1.5引入的Semaphore类,用于多线程环境下资源访问控制。通过实例展示如何设置许可证数量,控制线程并发访问,确保资源访问的同步与互斥。 https://blog.csdn.net/zhangphil/article/details/83410270

 

http://www.xdnf.cn/news/13051.html

相关文章:

  • chili3d调试笔记3 加入c++ 大模型对话方法 cmakelists精读
  • PY32F003+TIM+外部中断实现对1527解码
  • 【Test Test】灰度化和二值化处理图像
  • 6TOPS算力NPU加持!RK3588如何重塑8K显示的边缘计算新边界
  • 嵌入式音视频开发指南:从MPP框架到QT实战全解析
  • 3D 视觉赋能仓储精准高效:ID Logistics 与 Stereolabs 的创新合作之旅
  • Java开发中的常用注解
  • 字符串系列一>最长回文子串
  • 给予FLUX更好的控制:FLUX.1-dev-ControlNet-Union-Pro-2.0
  • Redis——网络模型之IO讲解
  • 大模型微服务架构模块实现方案,基于LLaMA Factory和Nebius Cloud实现模型精调的标准流程及代码
  • Android——动画
  • IPTV电视信息发布直播点播系统:营造数字化个性化融合化多媒体IPTV电视信息发布平台
  • 预训练与微调:大模型如何“学习知识”?
  • Python 网络爬虫基础理论与实战指南
  • 【每日八股】复习计算机网络 Day1:TCP 的头部结构 + TCP 确保可靠传输 + TCP 的三次握手
  • 【漫话机器学习系列】209.均值的标准误差(Standard Error of the Mean)
  • 完整的 .NET 6 分布式定时任务实现(Hangfire + Redis 分布式锁)
  • 故障诊断常用算法
  • 2025妈妈杯数学建模D题完整分析论文
  • Kubernetes Pod 调度策略:从基础到进阶
  • java面向对象09:方法的重写
  • PyTorch入门------卷积神经网络
  • TCP/IP和UDP协议的发展历程
  • POSIX 信号量(Semaphore)
  • MacOS怎么显示隐藏文件
  • Vue3 实战:打造多功能旅游攻略选项卡页面
  • 记录学习的第二十九天
  • unity TEngine学习记录3
  • 精准计量+AI管控——安科瑞助力高校水电管理数字化转型