【问题标题】:How to create a Thread pool in Kotlin如何在 Kotlin 中创建线程池
【发布时间】:2017-05-20 01:32:10
【问题描述】:

我想在 Kotlin 中创建一个线程池。我一直在互联网上搜索几个小时,但我找不到一个例子。谁能提供例子。谢谢。

【问题讨论】:

  • 像在 Java 代码中一样使用标准的线程池。

标签: kotlin


【解决方案1】:
    val executor = Executors.newFixedThreadPool(5)
    for (i in 0..9) {
        val worker = Runnable { println("Hello this is thread " + i) }
        executor.execute(worker)
    }
    executor.shutdown()
    while (!executor.isTerminated) {
    }
    println("Finished all threads")

【讨论】:

  • 在调用.shutdown() 之后,您不应该需要while (!isTerminated) 循环......对吗?在这一点上,他们都不能保证被终止。如果不是,那么应该有一种比紧的 while 循环更不占用资源的方法。
  • 您可以使用awaitTermination 等待所有任务终止,而不是使用紧的while 循环。
【解决方案2】:
suspend fun withFixedThreadPool(numThreads: Int, borrow: suspend (ExecutorCoroutineDispatcher) -> Unit) =
    Executors.newFixedThreadPool(numThreads).asCoroutineDispatcher().use { borrow(it) }

【讨论】:

  • 你需要解释你的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-05
  • 2015-06-07
  • 2015-03-28
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多