当前位置:网站首页>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
}边栏推荐
- Vulnerability management mistakes that CIOs still make
- 【AI玩家养成记】用AI识别邻居家旺财是什么品种
- 2022年煤炭生产经营单位(安全生产管理人员)考试题模拟考试平台操作
- AGCO AI frontier promotion (6.24)
- How to avoid serious network security accidents?
- #云原生征文#Ingress案例实战
- Goldfish rhca memoirs: do447 manage lists and credentials -- create machine credentials for the access list host
- **Unity中莫名其妙得小问题-灯光和天空盒
- Troubleshooting the kubernetes problem: deleting the rancher's namespace by mistake causes the node to be emptied
- Eight major trends in the industrial Internet of things (iiot)
猜你喜欢

These default routes and static routes can not be configured and deployed. What kind of network workers are they!

Who is the fish and who is the bait? Summary of honeypot recognition methods from the perspective of red team

图扑软件数字孪生海上风电 | 向海图强,奋楫争先

每日一题day8-515. 在每个树行中找最大值

常识知识点

10 个 Reduce 常用“奇技淫巧”

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

Eight major trends in the industrial Internet of things (iiot)

Activity lifecycle

Without home assistant, zhiting can also open source access homekit and green rice devices?
随机推荐
kotlin 初始化块
Liux command
Process basic properties
Kotlin language features
青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”
Why is open source technology so popular in the development of audio and video streaming media platform?
数据科学家面临的七大挑战及解决方法
How does webrtc obtain video stream data on the C ++ side?
万用表的使用方法
美国会参议院推进两党枪支安全法案
真正的项目经理强者,都是闭环高手!
Prometheus PushGateway 碎碎念
服务可见可观测性
Source code analysis handler interview classic
On the difference between process and thread
Geological disaster early warning monitoring RTU
一个团队可以既做项目又做产品吗?
kotlin 数组、集合和 Map 的使用
Appium installation
I have fundamentally solved the problem of wechat occupying mobile memory