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