【问题标题】:Java thread pool with single thread not behaving as expected具有单线程的 Java 线程池未按预期运行
【发布时间】:2019-11-17 16:25:38
【问题描述】:

我正在创建一个只有一个线程的线程池执行器,并在 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()) {

}

【问题讨论】:

    标签: java kotlin concurrency kotlin-coroutines


    【解决方案1】:

    您每次调用您的方法时都在调用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){ ... }
    

    【讨论】:

    • 添加 - 命名约定 pool{N}-thr​​ead-{M} 基本上意味着线程是创建的第 N 个池中的第 M 个线程。例如,pool9-thread-1 表示它是第 9 个池的第一个线程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多