具有单线程的 Java 线程池未按预期运行

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)

Thi*_*ilo 5

你在呼唤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)

  • 添加 - 命名约定 pool{N}-thr​​ead-{M} 基本上意味着该线程是创建的第 N 个池中的第 M 个线程。例如- pool9-thread-1 表示它是第 9 个池的第一个线程。 (2认同)