当前位置:网站首页>Kotlin coroutine context and scheduler
Kotlin coroutine context and scheduler
2022-06-24 13:40:00 【day_ moon】
//1. Scheduler Co process builder ( Co scheduler ) Dispatch the coroutine to run in the thread
fun mainDispatcher()= runBlocking {
launch {
println("launch ${Thread.currentThread().name} ..")// The main thread
}
launch(Dispatchers.Unconfined) {
println("Unconfined ${Thread.currentThread().name} ..")// The main thread It's a different mechanism
}
launch(Dispatchers.Default) {
println("Default ${Thread.currentThread().name} ..")// Background thread pool
}
launch(newSingleThreadContext("newSingleThreadContext")) {
println("thread ${Thread.currentThread().name} ..")// Create a new thread
}
}
//2. The scheduler starts a coroutine in the caller thread , But it just runs to the first hanging point .
// After suspend , It will restore the coroutines in the thread , The coroutine is completely determined by the suspended function called
// The scheduler is inherited from the external scope by default
fun mainUnconfined()= runBlocking {
launch(Dispatchers.Unconfined) {
println("Unconfined ${Thread.currentThread().name} ..")// The main thread
delay(1000)
println("Unconfined ${Thread.currentThread().name} ..end")// Thread pool
}
launch {
println("launch ${Thread.currentThread().name} ..")// The main thread
delay(1000)
println("launch ${Thread.currentThread().name} ..end")// The main thread
}
}
//3. debugging
fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")// Print thread name
fun mainLog()= runBlocking {
var a=async {
delay(1000)
log("a coroutines ")
1
}
var b=async {
delay(2000)
log("b coroutines ")
2
}
log("a+b=${a.await()+b.await()}")
}
//4. Inter process switching
fun mainwithContext() {
newSingleThreadContext("Ctx1").use { ctx1 ->
newSingleThreadContext("Ctx2").use { ctx2 ->
runBlocking(ctx1) {// Use... To display the specified context runBlocking
log("Started in ctx1")//[Ctx1] Started in ctx1
withContext(ctx2) {// Change the context of a collaboration and keep it in another collaboration
log("Working in ctx2")//[Ctx2] Working in ctx2
}
log("Back to ctx1")//[Ctx1] Back to ctx1
}
}
}//use Release when no longer needed newSingleThreadContext Created thread
}
//5. Zixie Cheng
fun mainChildren_coroutine()= runBlocking {
val facher=launch {
GlobalScope.launch {// GlobalScope Start the coroutines It's co-operative Job No father , Therefore, it is not limited by its startup scope and independent operation scope
println("GlobalScope ..")
delay(1000)
println("GlobalScope ..end")
}
launch {
delay(100)
println("launch ..")
delay(1000)
println("launch ..end")
}
}
delay(500)
facher.cancel()// When the parent collaboration is cancelled The subprocess is also cancelled launch The collaboration of has not been completed
delay(1000)
println("facher ..end")
}
//6. Parent process
fun mainfacher_coroutine()= runBlocking {
val facher=launch {
GlobalScope.launch {// GlobalScope Start the coroutines It's co-operative Job No father , Therefore, it is not limited by its startup scope and independent operation scope
println("GlobalScope ..")
delay(1000)
println("GlobalScope ..end")
}
launch {
delay(100)
println("launch ..")
delay(1000)
println("launch ..end")
}
}
delay(500)
// facher.join()// When the parent process waits for the child process to finish launch The cooperation process of is completed
delay(1000)
println("facher ..end")
}
//7. The coroutine is named for debugging
fun maincoroutine_name()= runBlocking(CoroutineName("main")) {
log("Started")
val a=launch(CoroutineName("a")) {
delay(1000)
log(" a..")
}
val b= launch(CoroutineName("b")) {
delay(1000)
log(" ..b")
}
println(" ..end")
}
//8. The coroutine is named for debugging
fun mainCoroutineName()= runBlocking() {
launch(Dispatchers.Default+ CoroutineName("test")) {
println("thread is ${Thread.currentThread().name}")
}
println(" ..end")
}
//9. Thread local data ThreadLocal
fun mainThreadLocal()= runBlocking() {
val threadLocal=ThreadLocal<String>()
threadLocal.set("main")
println(" Current thread : ${Thread.currentThread()},threadLocal Value : '${threadLocal.get()}'")
val job = launch(Dispatchers.Default+ threadLocal.asContextElement(value = "launch")) {
println("Launch Current thread : ${Thread.currentThread()}, threadLocal Value : '${threadLocal.get()}'")// DefaultDispatcher-worker-1,5,main launch
yield()
println("yield, Current thread : ${Thread.currentThread()}, threadLocal Value : '${threadLocal.get()}'")// DefaultDispatcher-worker-1,5,main launch
}
job.join()
println("end .. current thread: ${Thread.currentThread()}, threadLocal Value : '${threadLocal.get()}'") //Thread[main,5,main] 'main'
job.cancel()
}
//10 Process scope
fun mainCoroutinescope() = runBlocking<Unit> {
val activity = ActivityTest()
activity.doSomething() // function
println(" The destruction ...")
activity.destroy()
delay(1000) // After destruction , No more printing
}ActivityTest class
// be used for 10 Co process scoped
class ActivityTest : CoroutineScope by CoroutineScope(Dispatchers.Default) {// Realization CoroutineScope Interface The default factory function uses delegates
fun destroy() {
cancel() // Extended to CoroutineScope
}
fun doSomething() {
// repeat come from CoroutineScope Of
repeat(10) { i ->
launch {
delay((i + 1) * 200L) // variable delay 200ms, 400ms, ... etc
println("Coroutine $i is done")
}
}
}
}边栏推荐
- I have fundamentally solved the problem of wechat occupying mobile memory
- 10 个 Reduce 常用“奇技淫巧”
- SAP QM qac1 transaction code cannot modify the quantity in the inspection lot containing Hu
- hands-on-data-analysis 第三单元 模型搭建和评估
- 快速了解常用的消息摘要算法,再也不用担心面试官的刨根问底
- Implement Domain Driven Design - use ABP framework - create entities
- kotlin 异步流
- 万用表的使用方法
- Beauty of script │ VBS introduction interactive practice
- 【sdx62】WCN685X IPA注册失败问题分析及解决方案
猜你喜欢

谁是鱼谁是饵?红队视角下蜜罐识别方式汇总

Teach you how to use airtestide to connect your mobile phone wirelessly!

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

快速了解常用的消息摘要算法,再也不用担心面试官的刨根问底

黄金年代入场券之《Web3.0安全手册》

CVPR 2022 - Interpretation of selected papers of meituan technical team

敏捷之道 | 敏捷开发真的过时了么?

How to avoid serious network security accidents?

3. caller service call - dapr

首席信息安全官仍然会犯的漏洞管理错误
随机推荐
[one picture series] one picture to understand Tencent Qianfan ipaas
kotlin 继承、类、重载
服务可见可观测性
Talk about GC of JVM
面试官:MySQL 数据库查询慢,除了索引问题还可能是什么原因?
Quickly understand the commonly used message summarization algorithms, and no longer have to worry about the thorough inquiry of the interviewer
常识知识点
美国会参议院推进两党枪支安全法案
Android kotlin Encyclopedia
Eight major trends in the industrial Internet of things (iiot)
码农版隐秘的角落:作为开发者最讨厌的5件事
图扑软件数字孪生海上风电 | 向海图强,奋楫争先
How long will it take to open a mobile account? Is online account opening safe?
Redis scenario
Coinbase将推出首个针对个人投资者的加密衍生产品
Kotlin inheritance, class, overload
Hands on data analysis unit 3 model building and evaluation
kotlin 协程上下文和调度器
SAP QM qac1 transaction code cannot modify the quantity in the inspection lot containing Hu
Goldfish rhca memoirs: do447 manage lists and credentials -- create machine credentials for the access list host