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()}'")    
}

 

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