当前位置:网站首页>kotlin 协程上下文和调度器
kotlin 协程上下文和调度器
2022-06-24 12:53:00 【day_moon】
//1.调度器 协程构造器(协程调度器) 将协程分派到线程中运行
fun mainDispatcher()= runBlocking {
launch {
println("launch ${Thread.currentThread().name} ..")//主线程
}
launch(Dispatchers.Unconfined) {
println("Unconfined ${Thread.currentThread().name} ..")//主线程 它是一种不同的机制
}
launch(Dispatchers.Default) {
println("Default ${Thread.currentThread().name} ..")//后台线程池
}
launch(newSingleThreadContext("newSingleThreadContext")) {
println("thread ${Thread.currentThread().name} ..")//创建新线程
}
}
//2.调度器在调用者线程中启动一个协程,但它仅仅只是运行到第一个挂起点。
// 在挂起之后,它将恢复线程中的协程,该协程完全由调用的挂起函数决定
//调度器是默认继承于外部的协程作用域的
fun mainUnconfined()= runBlocking {
launch(Dispatchers.Unconfined) {
println("Unconfined ${Thread.currentThread().name} ..")//主线程
delay(1000)
println("Unconfined ${Thread.currentThread().name} ..end")//线程池
}
launch {
println("launch ${Thread.currentThread().name} ..")//主线程
delay(1000)
println("launch ${Thread.currentThread().name} ..end")//主线程
}
}
//3.调试
fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")//打印线程名
fun mainLog()= runBlocking {
var a=async {
delay(1000)
log("a协程")
1
}
var b=async {
delay(2000)
log("b协程")
2
}
log("a+b=${a.await()+b.await()}")
}
//4.在线程间切换
fun mainwithContext() {
newSingleThreadContext("Ctx1").use { ctx1 ->
newSingleThreadContext("Ctx2").use { ctx2 ->
runBlocking(ctx1) {//对显示指定的上下文使用 runBlocking
log("Started in ctx1")//[Ctx1] Started in ctx1
withContext(ctx2) {//更改协程的上下文并同时仍然保持在另一个协程中
log("Working in ctx2")//[Ctx2] Working in ctx2
}
log("Back to ctx1")//[Ctx1] Back to ctx1
}
}
}//use 在不再需要时释放 newSingleThreadContext 所创建的线程
}
//5.子协程
fun mainChildren_coroutine()= runBlocking {
val facher=launch {
GlobalScope.launch {// GlobalScope 启动协程 协程的 Job 没有父级,所以不受其启动的作用域和独立运作范围的限制
println("GlobalScope ..")
delay(1000)
println("GlobalScope ..end")
}
launch {
delay(100)
println("launch ..")
delay(1000)
println("launch ..end")
}
}
delay(500)
facher.cancel()//当父协程取消 子协程也被取消 launch的协程没有运行完
delay(1000)
println("facher ..end")
}
//6.父协程
fun mainfacher_coroutine()= runBlocking {
val facher=launch {
GlobalScope.launch {// GlobalScope 启动协程 协程的 Job 没有父级,所以不受其启动的作用域和独立运作范围的限制
println("GlobalScope ..")
delay(1000)
println("GlobalScope ..end")
}
launch {
delay(100)
println("launch ..")
delay(1000)
println("launch ..end")
}
}
delay(500)
// facher.join()//当父协程会等待子协程完才结束 launch的协程运行完
delay(1000)
println("facher ..end")
}
//7.协程命名以便调试
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.协程命名以便调试
fun mainCoroutineName()= runBlocking() {
launch(Dispatchers.Default+ CoroutineName("test")) {
println("thread is ${Thread.currentThread().name}")
}
println(" ..end")
}
//9.线程局部数据 ThreadLocal
fun mainThreadLocal()= runBlocking() {
val threadLocal=ThreadLocal<String>()
threadLocal.set("main")
println("当前线程: ${Thread.currentThread()},threadLocal的值: '${threadLocal.get()}'")
val job = launch(Dispatchers.Default+ threadLocal.asContextElement(value = "launch")) {
println("Launch 当前线程: ${Thread.currentThread()}, threadLocal的值: '${threadLocal.get()}'")// DefaultDispatcher-worker-1,5,main launch
yield()
println("yield, 当前线程: ${Thread.currentThread()}, threadLocal的值: '${threadLocal.get()}'")// DefaultDispatcher-worker-1,5,main launch
}
job.join()
println("end .. current thread: ${Thread.currentThread()}, threadLocal的值: '${threadLocal.get()}'") //Thread[main,5,main] 'main'
job.cancel()
}
//10 协程作用域
fun mainCoroutinescope() = runBlocking<Unit> {
val activity = ActivityTest()
activity.doSomething() //运行
println("销毁...")
activity.destroy()
delay(1000) //销毁后,不再打印
}ActivityTest类
//用于 10 协程作用域的
class ActivityTest : CoroutineScope by CoroutineScope(Dispatchers.Default) {//实现 CoroutineScope接口 默认工厂函数使用委托
fun destroy() {
cancel() // 扩展于CoroutineScope
}
fun doSomething() {
// repeat来自CoroutineScope的
repeat(10) { i ->
launch {
delay((i + 1) * 200L) // variable delay 200ms, 400ms, ... etc
println("Coroutine $i is done")
}
}
}
}边栏推荐
- Evolution of the message module of the play live series (3)
- The introduction of MySQL memory parameters is divided into two categories: thread exclusive and global sharing
- AGCO AI frontier promotion (6.24)
- CVPR 2022 | 美团技术团队精选论文解读
- [log service CLS] Tencent cloud log service CLS accesses CDN
- Goldfish rhca memoirs: do447 manage lists and credentials -- create machine credentials for the access list host
- 每日一题day8-515. 在每个树行中找最大值
- Explain the difference between iaas/paas/saas by cooking rice
- 数据科学家面临的七大挑战及解决方法
- Kotlin interface generic covariant inversion
猜你喜欢

面试官:MySQL 数据库查询慢,除了索引问题还可能是什么原因?

CVPR 2022 | interprétation de certains documents de l'équipe technique de meituan

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

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

硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件

10 个 Reduce 常用“奇技淫巧”

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

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

Comparator sort functional interface

华为 PC 逆势增长,产品力决定一切
随机推荐
Liux command
kotlin 接口 泛型 协变 逆变
Kotlin keyword extension function
Megacli online management raid installation and use steps
首席信息安全官仍然会犯的漏洞管理错误
黄楚平主持召开定点联系珠海工作视频会议 坚决落实省委部署要求 确保防疫情、稳经济、保安全取得积极成效
Redis scenario
Integrated API interface code of domestic express companies for intra city distribution and ordering - Express 100
源码解析 Handler 面试宝典
系统测试主要步骤
Getting started with the go Cobra command line tool
【sdx62】WCN685X IPA不生效问题分析及解决方案
ERR AUTH&lt; password&gt; called without anypassword configured for the default user. Ar
YOLOv6:又快又准的目标检测框架开源啦
Internet of things? Come and see Arduino on the cloud
Opengauss kernel: simple query execution
CVPR 2022 - Interpretation of selected papers of meituan technical team
kotlin 初始化块
CPU status information us, sy and other meanings
kotlin 协程 lanch 详解