相关疑难解决方法(0)

使用 Kotlin 协程的多线程

我正在试验Kotlin 协程并有以下代码:

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

这是我的输出:

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

multithreading jvm kotlin kotlinx.coroutines

3
推荐指数
1
解决办法
3050
查看次数

标签 统计

jvm ×1

kotlin ×1

kotlinx.coroutines ×1

multithreading ×1