当前位置:网站首页>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")
}
}
}
}边栏推荐
- 这几个默认路由、静态路由的配置部署都不会,还算什么网工!
- 系统测试主要步骤
- Activity生命周期
- 黄楚平主持召开定点联系珠海工作视频会议 坚决落实省委部署要求 确保防疫情、稳经济、保安全取得积极成效
- Main steps of system test
- I have fundamentally solved the problem of wechat occupying mobile memory
- Talk about GC of JVM
- Getting started with the go Cobra command line tool
- Beauty of script │ VBS introduction interactive practice
- Google Earth Engine——1999-2019年墨累全球潮汐湿地变化 v1 数据集
猜你喜欢

数据科学家面临的七大挑战及解决方法

【5G NR】5G NR系统架构

青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”

Hands on data analysis unit 3 model building and evaluation

3. caller service call - dapr

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

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

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

系统测试主要步骤

The data value reported by DTU cannot be filled into Tencent cloud database through Tencent cloud rule engine
随机推荐
8 lines of code to teach you how to build an intelligent robot platform
RAID5 array recovery case tutorial of a company in Shanghai
Party, Google's autoregressive Wensheng graph model
Goldfish rhca memoirs: do447 manage lists and credentials -- create machine credentials for the access list host
Why did the audio and video based cloud conference usher in a big explosion of development?
Source code analysis handler interview classic
Activity生命周期
The hidden corner of codefarming: five things that developers hate most
Understanding openstack network
The 35 "top 100 counties" of tmall 618 agricultural products come from the central and western regions and Northeast China
hands-on-data-analysis 第三单元 模型搭建和评估
美国会参议院推进两党枪支安全法案
TCP triple handshake
Getting started with the lvgl Library - colors and images
3. Caller 服务调用 - dapr
Detailed explanation of kotlin collaboration lanch
每日一题day8-515. 在每个树行中找最大值
谁是鱼谁是饵?红队视角下蜜罐识别方式汇总
C语言中常量的定义和使用
How can the new webmaster avoid the ups and downs caused by SEO optimization?