Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asynchronous 如何在jvm kotlin中使用wait或async?_Asynchronous_Kotlin_Async Await_Coroutine - Fatal编程技术网

Asynchronous 如何在jvm kotlin中使用wait或async?

Asynchronous 如何在jvm kotlin中使用wait或async?,asynchronous,kotlin,async-await,coroutine,Asynchronous,Kotlin,Async Await,Coroutine,我正在尝试用kotlin await/async函数编写一个示例,它的工作原理应该与c#await示例相同。它可以正常工作,但我不确定是否正确理解了这两个方面,也许我创建了太多的异步协同路由。有人能给我一些建议吗?谢谢 package-diki.test 导入kotlinx.coroutines.experimental.async 导入kotlinx.coroutines.experimental.runBlocking 导入org.apache.commons.lang3.RandomUt

我正在尝试用kotlin await/async函数编写一个示例,它的工作原理应该与c#await示例相同。它可以正常工作,但我不确定是否正确理解了这两个方面,也许我创建了太多的异步协同路由。有人能给我一些建议吗?谢谢

package-diki.test
导入kotlinx.coroutines.experimental.async
导入kotlinx.coroutines.experimental.runBlocking
导入org.apache.commons.lang3.RandomUtils
fun main(args:Array)=运行阻塞{
val start=System.currentTimeMillis()
开始按钮单击()。等待();
println(“time=“+(System.currentTimeMillis()-start))
}
趣味开始按钮点击()=异步{
CreateMultipleTaskAsync().await()
}
fun createMultipleTaskAsync()=异步{
val d1=ProcessURLAsync(“http://a”)
val d2=ProcessURLAsync(“http://a1")
val d3=ProcessURLAsync(“http://a111")
val d1r=d1.await()
val d2r=d2.await()
val d3r=d3.await()
}
fun ProcessURLAsync(url:String)=异步{
sleep(RandomUtils.nextLong(5001000))//模拟网络作业
url.length
}

async/wait
对于
CreateMultipleTasksAsync
startButton\u单击
无效。 只需让它们
挂起
功能即可

和+1表示
delay
而不是
Thread.sleep

而不是
Thread.sleep()
使用
delay
协同程序。还可以查看
awaitAll()
签出正式文档:
package diki.test

import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.runBlocking
import org.apache.commons.lang3.RandomUtils

fun main(args: Array<String>) = runBlocking {
    val start = System.currentTimeMillis()
    startButton_Click().await();
    println("time=" + (System.currentTimeMillis() - start))
}

fun startButton_Click() = async {
    CreateMultipleTasksAsync().await()
}

fun CreateMultipleTasksAsync() = async {
    val d1 = ProcessURLAsync("http://a")
    val d2 = ProcessURLAsync("http://a1")
    val d3 = ProcessURLAsync("http://a111")
    val d1r = d1.await()
    val d2r = d2.await()
    val d3r = d3.await()
}

fun ProcessURLAsync(url: String) = async {
    Thread.sleep(RandomUtils.nextLong(500, 1000))//mock network job
    url.length
}