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
?