Kotlin互斥锁Mutex协程withLock实现同步
Kotlin互斥锁Mutex协程withLock实现同步
Mutex与Java语言中的Semaphore类似。
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLockfun main() {val A = "a"val B = "b"val C = "c"val repeatCnt = 2//随机协程并发runBlocking {launch(Dispatchers.IO) {print(repeatCnt, A)}launch(Dispatchers.IO) {print(repeatCnt, B)}launch(Dispatchers.IO) {print(repeatCnt, C)}}println("#####")runBlocking {delay(10)}val mutex = Mutex()//使用 Mutex 协程同步runBlocking {launch(Dispatchers.IO) {mutex.withLock {print(repeatCnt, A)}}launch(Dispatchers.IO) {mutex.withLock {print(repeatCnt, B)}}launch(Dispatchers.IO) {mutex.withLock {print(repeatCnt, C)}}}
}private fun print(repeatCnt: Int, tag: String) {runBlocking {repeat(repeatCnt) { it ->val d = (Math.random() * 10).toLong()delay(d)println("$tag-$it $d ${System.currentTimeMillis()}")}}
}
运行输出:
a-0 1 1758548447902
a-1 0 1758548447903
b-0 8 1758548447906
c-0 7 1758548447906
c-1 0 1758548447906
b-1 4 1758548447922
#####
a-0 6 1758548447969
a-1 5 1758548447984
b-0 6 1758548447999
b-1 9 1758548448015
c-0 2 1758548448030
c-1 8 1758548448045
Java与Kotlin中Semaphore相关文章:
https://blog.csdn.net/zhangphil/article/details/132356885
https://blog.csdn.net/zhangphil/article/details/147069067
https://blog.csdn.net/zhangphil/article/details/83410270