rah*_*008 0 java concurrency kotlin kotlin-coroutines
我正在创建一个只有一个线程的线程池执行器,并在 Kotlin 程序中使用 Kotlin 的 asCoroutineDispatcher() 方法。当我从循环中启动多个协程并记录线程名称时,我看到不同的名称 - pool1-thread1、pool3-thread1、pool9-thread-1 等。为什么当我使用单线程作为池时会有多个线程?Kotlin 是否以不同的方式管理线程池?
// this is executed in loop
fun executeTask(url: String) {
GlobalScope.launch {
val result = runAsync(url)
Log.d("coroutineCheck", "$url\t\tStatus:$result")
}
}
//some blocking n/w IO goes in this method
//I log the thread name here
suspend fun runAsync(url: String): String = withContext(Executors.newFixedThreadPool(1).asCoroutineDispatcher()) {
}
Run Code Online (Sandbox Code Playgroud)
你在呼唤newFixedThreadPool你每次打电话给你的方法时,反复营造了全新的池。
您将希望共享同一个 Executor。
// singleton to put somewhere, may also need to shut it down eventually
val dispatcher = Executors.newFixedThreadPool(1).asCoroutineDispatcher()
suspend func runAsync(url: String): String = withContext(dispatcher){ ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |