异步工作,但等待

时间:2017-11-17 02:30:52

标签: java intellij-idea kotlin open-source

我有以下代码。

我无法理解为什么会这样。我发现没有关于SO的现有答案。我试着直接等待分配了tenny和twy,但这也不起作用。

我不认为依赖项存在问题,因为aysnc有效。我还发布了build.gradle文件。

import kotlinx.coroutines.experimental.async

fun main(args: Array<String>) {
    async{
        val tenny = star_ten(1)
        val twy =star_two(10)

        println()
        println(twy.await()+tenny.await())
        println()
    }
}

fun star_two(num:Int):Int{
    return num * 2
}
fun star_ten(num:Int):Int{
    return num * 10
}

我的build.gradle是

group 'org.nul.cool'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.1.60'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'java'
apply plugin: 'kotlin'

kotlin {
    experimental {
        coroutines 'enable'
    }
}



sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.19.2"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

1 个答案:

答案 0 :(得分:2)

您收到await()未解决的引用,因为您的star_twostar_ten函数返回Int,因此tennytwy变量是只是Intawait()函数在Deferred上声明。简而言之,您在这些功能中不做任何异步操作,因此无需等待。

使这些函数异步运行的一种方法是将它们声明为挂起函数,并在异步块中调用它们。这样的事情(未经测试)......

async{
    val tenny = async { star_ten(1) } //Should be Deferred<Int>
    val twy = async { star_two(10)}   //Should be Deferred<Int>
    println(twy.await() + tenny.await())
}

suspend fun star_two(num:Int): Int = num * 2
suspend fun star_ten(num:Int): Int = num * 10

Guide to kotlinx.coroutines by example页面有很多很好的例子,尤其是this section