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