当前位置:网站首页>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") } } } }
边栏推荐
- Interviewer: the MySQL database is slow to query. What are the possible reasons besides the index problem?
- Manuel d'entrevue du gestionnaire de l'analyse des sources
- 实现领域驱动设计 - 使用ABP框架 - 创建实体
- Preparation and operation & Maintenance Guide for 'high concurrency & high performance & high availability service program'
- Beauty of script │ VBS introduction interactive practice
- kotlin 初始化块
- 【sdx62】WCN685X IPA不生效问题分析及解决方案
- Implement Domain Driven Design - use ABP framework - update operational entities
- 如何化解35岁危机?华为云数据库首席架构师20年技术经验分享
- 3. Caller 服务调用 - dapr
猜你喜欢
3. caller service call - dapr
黄金年代入场券之《Web3.0安全手册》
Beauty of script │ VBS introduction interactive practice
Comparator 排序函数式接口
CVPR 2022 | interprétation de certains documents de l'équipe technique de meituan
图扑软件数字孪生海上风电 | 向海图强,奋楫争先
首席信息安全官仍然会犯的漏洞管理错误
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
Getting started with the go Cobra command line tool
1. Snake game design
随机推荐
Main steps of system test
Gateway processing flow of zuul source code analysis
kotlin 继承、类、重载
如何化解35岁危机?华为云数据库首席架构师20年技术经验分享
go Cobra命令行工具入门
每日一题day8-515. 在每个树行中找最大值
Android kotlin 大全
SAP QM qac1 transaction code cannot modify the quantity in the inspection lot containing Hu
How stupid of me to hire a bunch of programmers who can only "Google"!
Best practices of swagger in egg project
CVPR 2022 | 美团技术团队精选论文解读
金鱼哥RHCA回忆录:DO447管理清单和凭据--为访问清单主机创建机器凭据
Preparation and operation & Maintenance Guide for 'high concurrency & high performance & high availability service program'
Goldfish rhca memoirs: do447 manage lists and credentials -- create machine credentials for the access list host
The second phase of freshman engineering education seminar is to enroll in the China 100 school peer program
Memory introduction
Implement Domain Driven Design - use ABP framework - update operational entities
Richard Sutton, the father of reinforcement learning, paper: pursuing a general model for intelligent decision makers
Quickly understand the commonly used message summarization algorithms, and no longer have to worry about the thorough inquiry of the interviewer
YOLOv6:又快又准的目标检测框架开源啦