[英]Java thread pool with single thread not behaving as expected
我正在创建仅具有一个线程的线程池执行程序,并在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()) {
}
每次调用方法时,都会调用newFixedThreadPool
,从而反复创建全新的池。
您将要共享相同的执行器。
// 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){ ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.