当前位置:网站首页>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")
}
}
}
}边栏推荐
- ERR AUTH&lt; password&gt; called without anypassword configured for the default user. Ar
- Vipshop's "special sale" business is no longer easy to do?
- 问个sql view的问题
- Why does the kubernetes environment require that bridge NF call iptables be enabled?
- CPU status information us, sy and other meanings
- Appium installation
- 10 个 Reduce 常用“奇技淫巧”
- Who is the fish and who is the bait? Summary of honeypot recognition methods from the perspective of red team
- 首席信息安全官仍然会犯的漏洞管理错误
- On the difference between process and thread
猜你喜欢

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

Understanding openstack network

Party, Google's autoregressive Wensheng graph model

Creation and use of unified links in Huawei applinking

Developer survey: rust/postgresql is the most popular, and PHP salary is low

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

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

这几个默认路由、静态路由的配置部署都不会,还算什么网工!

Cloud native essay solicitation progress case practice

One article explains R & D efficiency! Your concerns are
随机推荐
TCP triple handshake
DTU上报的数据值无法通过腾讯云规则引擎填入腾讯云数据库中
Integrate API interface parameter Dictionary of accounts of multiple local distribution companies - Express 100
源码解析 Handler 面试宝典
[one picture series] one picture to understand Tencent Qianfan apaas
CVPR 2022 | 美团技术团队精选论文解读
Developer survey: rust/postgresql is the most popular, and PHP salary is low
Beauty of script │ VBS introduction interactive practice
The 35 "top 100 counties" of tmall 618 agricultural products come from the central and western regions and Northeast China
SAP QM qac1 transaction code cannot modify the quantity in the inspection lot containing Hu
华为 PC 逆势增长,产品力决定一切
SYSTEMd common component description
Vulnerability management mistakes that CIOs still make
快速了解常用的消息摘要算法,再也不用担心面试官的刨根问底
Understanding openstack network
Source code analysis handler interview classic
kotlin 继承、类、重载
Prometheus pushgateway
CPU process priority
What is the difference between sap QM and UD for inspection lots with hum?