Kotlin协程 ThreadLocal

Kotlin中有一个和Java的ThreadLocal概念差不多的东西, ThreadLocal是Thread私有的,ThreadLocal.asContextElement是coroutine私有的. 注意在launch的时候指定值.无论coroutine在线程池的哪个线程. 最终获取到的都是coroutine私有的数据.

val threadLocal = ThreadLocal<String?>() // declare thread-local variable
 
fun main() = runBlocking<Unit> {
    threadLocal.set("main")
    println("Pre-main, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
    val job = launch(Dispatchers.Default + threadLocal.asContextElement(value = "launch")) {
        println("Launch start, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
        yield()
        println("After yield, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
    }
    job.join()
    println("Post-main, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")    
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章