如何在Kotlin中创建一个线程池

Met*_*lel 3 kotlin

我想在Kotlin中创建一个线程池.我一直在互联网上搜索几个小时,我不能得到一个例子.任何人都可以举例.谢谢.

Met*_*lel 9

    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")
Run Code Online (Sandbox Code Playgroud)

  • 在调用 `.shutdown()` 之后,您不应该需要 `while (!isTermminate)` 循环......对吧?到那时,他们不都保证会被终止吗?如果不是,那么应该有一种比紧密的 while 循环消耗资源更少的方法。 (2认同)