使用Kotlin协程的multithreading

我正在用Kotlin Coroutines进行试验,并有如下代码:

fun main(args: Array) = 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 

根据罗马的Elizarov对另一个与协程有关的问题的回答:

“启动只是创建新的协同程序,而CommonPool将协程分派给ForkJoinPool.commonPool(),而ForkJoinPool.commonPool()使用多个线程,因此可以在本例中的多个CPU上执行。

根据Java 8 文档 :

“对于需要单独或自定义池的应用程序,可以使用给定的目标并行级别构建ForkJoinPool;默认情况下,该数量等于可用处理器的数量。

为什么只有3个工作线程被使用? 即使将异步任务的数量增加到1000以上,也有相同的3个工作线程。

我的配置:具有双核CPU的Mac / High Sierra(带有超线程 ,因此有4个可见内核),Kotlin 1.2,kotlinx-coroutines-core:0.19.3和JVM 1.8

如果你看一下CommonPool的实现,你会注意到它正在处理java.util.concurrent.ForkJoinPool或者一个具有以下大小的线程池:

 (Runtime.getRuntime().availableProcessors() - 1).coerceAtLeast(1) 

有了4可用的处理器,这将导致3答案为什么你看到3个工作线程。

ForkJoinPool -size可以如下确定(将是相同的):

 ForkJoinPool.commonPool().parallelism