我正在尝试Kotlin 协程 https://kotlinlang.org/docs/reference/coroutines.html并有以下代码:
fun main(args: Array<String>) = runBlocking {
val cores = Runtime.getRuntime().availableProcessors()
println("number of cores: $cores")
val jobs = List(10) {
async(CommonPool) {
delay(100)
println("async #$it on thread ${Thread.currentThread().name}")
}
}
jobs.forEach { it.join() }
}
这是我的输出:
number of cores: 4
async number:0 on thread ForkJoinPool.commonPool-worker-2
async number:2 on thread ForkJoinPool.commonPool-worker-3
async number:3 on thread ForkJoinPool.commonPool-worker-3
async number:4 on thread ForkJoinPool.commonPool-worker-3
async number:5 on thread ForkJoinPool.commonPool-worker-3
async number:1 on thread ForkJoinPool.commonPool-worker-1
async number:7 on thread ForkJoinPool.commonPool-worker-3
async number:6 on thread ForkJoinPool.commonPool-worker-2
async number:9 on thread ForkJoinPool.commonPool-worker-3
async number:8 on thread ForkJoinPool.commonPool-worker-1
根据罗曼·伊利扎罗夫的说法answer https://stackoverflow.com/a/43232925/3734457另一个与协程相关的问题:
“启动只是创建了新的协程,而 CommonPool 则调度
ForkJoinPool.commonPool() 的协程确实使用多个
线程,因此在此示例中在多个 CPU 上执行。”
根据Java 8文档 https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html:
“对于需要单独或自定义池的应用程序,
ForkJoinPool 可以用给定的目标并行度级别构建;
默认情况下,等于可用处理器的数量。”
为什么只使用了 3 个工作线程?即使我将异步任务数量增加到 1000+,仍然有 3 个工作线程。
我的配置:
Mac/High Sierra 带双核 cpu(带超线程 https://en.wikipedia.org/wiki/Hyper-threading,因此有 4 个可见核心)、Kotlin 1.2、kotlinx-coroutines-core:0.19.3 和 JVM 1.8
如果你看一下实施CommonPool https://github.com/Kotlin/kotlinx.coroutines/blob/master/core/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/CommonPool.kt,你会注意到它正在运行java.util.concurrent.ForkJoinPool
或具有以下大小的线程池:
(Runtime.getRuntime().availableProcessors() - 1).coerceAtLeast(1)
With 4
可用的处理器,这将导致3
这回答了为什么你会看到 3 个工作线程。
The ForkJoinPool
-size 可以确定如下(将相同):
ForkJoinPool.commonPool().parallelism
请参见这个答案 https://stackoverflow.com/a/53157947/8073652如果您使用的协程版本 >= 1.0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)