当前位置:网站首页>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")
            }
        }
    }
}
原网站

版权声明
本文为[day_ moon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241048331303.html