kotlin协程线程安全数据结构AtomicInteger原子同步
例如:
import kotlinx.coroutines.*
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
fun main(args: Array<String>) {
val coroutineDispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
val coroutineScope = CoroutineScope(coroutineDispatcher)
var count = AtomicInteger()
println(count)
runBlocking {
val job1 = coroutineScope.async {
repeat(500) {
count.incrementAndGet()
}
"OK1"
}
val job2 = coroutineScope.async {
delay(1_000)
"OK2"
}
println(job1.await())
println(job2.await())
}
println("count: ${count.get()}")
coroutineDispatcher.close() //如果没有这句,main()函数将不会退出,一直处于运行状态
}
输出:
0
OK1
OK2
count: 500