当前位置:网站首页>kotlin 共享可变状态和并发性
kotlin 共享可变状态和并发性
2022-06-24 12:58:00 【day_moon】
//1.并发引发的问题
suspend fun masRun(action:suspend()->Unit){
val a=100
val b=1000
val time= measureTimeMillis {
coroutineScope {
repeat(a){
launch {
repeat(b){action()}
}
}
}
}
println("actions: ${a * b} , 时间 $time ")//actions 100000 时间 49-80ms
}
@Volatile//Volatiles 是没有作用的
var count=0
fun main_masRun() = runBlocking {
withContext(Dispatchers.Default){
masRun{
count++
}
}
println("总数 = $count")//68147 counter而不进行任何同步
}
//2.线程安全的数据结构解决并发问题
suspend fun masVolatile (action:suspend()->Unit){
val a=100
val b=1000
val time= measureTimeMillis {
coroutineScope {
repeat(a){
launch {
repeat(b){action()}
}
}
}
}
println("actions: ${a * b} , 时间 $time ")//actions 100000 时间 52
}
var counts=AtomicInteger()//Volatiles 是没有作用的
fun main_volatile () = runBlocking {
withContext(Dispatchers.Default){
masVolatile{
counts.incrementAndGet()//之前是++
}
}
println("总数 = $counts")//100000
}
//3.以细粒度限制线程
val counterContext= newSingleThreadContext("counterContext")
fun main_countercontext() = runBlocking {
withContext(Dispatchers.Default){
masVolatile{
withContext(counterContext){//每个单独的增值操作都使用 withContext(counterContext)
count++
}
}
}
println("总数 = $count")//100000
}
//4.以粗粒度限制线程
val counterContexts= newSingleThreadContext("counterContext")
fun main_countercontexts() = runBlocking {
withContext(counterContexts){//线程限制是在比较大的范围内执行的
masVolatile{
count++
}
}
println("总数 = $count")//100000 4152
}
//5.互斥
val mutex= Mutex()
fun main_mutex() = runBlocking {
withContext(Dispatchers.Default){//线程限制是在比较大的范围内执行的
masVolatile{
mutex.withLock {//加锁 细粒度的
count++
}
}
}
println("总数 = $count")//100000 4152
}
//6.Actors
sealed class CounterMsg
object IncCounter : CounterMsg()//增加的对象
class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg()//请求的回应
fun CoroutineScope.counterActor() = actor<CounterMsg> {
var counter = 0 // actor状态
for (msg in channel) { // iterate over incoming messages
when (msg) {
is IncCounter -> counter++
is GetCounter -> msg.response.complete(counter)
}
}
}
fun main_actor() = runBlocking<Unit> {
val counter = counterActor() //增加一个actor
withContext(Dispatchers.Default) {
masVolatile {
counter.send(IncCounter)
}
}
//从actor得到发送来的值
val response = CompletableDeferred<Int>()
counter.send(GetCounter(response))
println("Counter = ${response.await()}")
counter.close() //关闭actor
}边栏推荐
- Integrate API interface parameter Dictionary of accounts of multiple local distribution companies - Express 100
- Ask a question about SQL view
- Kotlin keyword extension function
- 2022起重信号司索工(建筑特殊工种)复训题库及答案
- C语言中常量的定义和使用
- 8 lines of code to teach you how to build an intelligent robot platform
- CPU status information us, sy and other meanings
- 10 个 Reduce 常用“奇技淫巧”
- Comparator sort functional interface
- 2022年煤炭生产经营单位(安全生产管理人员)考试题模拟考试平台操作
猜你喜欢

Definition and use of constants in C language

C语言中常量的定义和使用

吉时利静电计宽测量范围

如何避免严重网络安全事故的发生?

工业物联网(IIoT)的八个主要趋势

Interviewer: the MySQL database is slow to query. What are the possible reasons besides the index problem?

万用表的使用方法

开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低

I have fundamentally solved the problem of wechat occupying mobile memory

Activity lifecycle
随机推荐
System status identifier 'hum' for SAP QM inspection lot
Android kotlin Encyclopedia
Getting started with the go Cobra command line tool
Sinomeni vine was selected as the "typical solution for digital technology integration and innovative application in 2021" of the network security center of the Ministry of industry and information te
3. caller service call - dapr
Beauty of script │ VBS introduction interactive practice
[AI player cultivation record] use AI to identify what kind of wealth is next door
2022年氟化工艺考试模拟100题及答案
码农版隐秘的角落:作为开发者最讨厌的5件事
What is the difference between sap QM and UD for inspection lots with hum?
Kotlin inheritance, class, overload
Activity生命周期
初中级开发如何有效减少自身的工作量?
kotlin 继承、类、重载
【AI玩家养成记】用AI识别邻居家旺财是什么品种
kotlin 关键字 扩展函数
redis 数据类型详解
Integrate the authorization interface code of intra city distribution account of multiple express companies nationwide - Express 100
kotlin 匿名函数 与 Lambda
国内首款开源MySQL HTAP数据库即将发布,三大看点提前告知