fun main(args: Array<String>) {
launch { // launch new coroutine in background and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello,") // main thread continues while coroutine is delayed
Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}
fun main(args: Array<String>) = runBlocking<Unit> {
val job = launch { // launch new coroutine and keep a reference to its Job
delay(1000L)
println("World!")
}
println("Hello,")
job.join() // wait until child coroutine completes
}
fun main(args: Array<String>) = runBlocking<Unit> {
val time = measureTimeMillis {
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
}
< p > 备用:
然而,我认为上述差异/方法是考虑Java/每个请求一个线程模型的结果。协程非常便宜,如果你想从某个任务/协程(假设是一个服务调用)的返回值中做一些事情,你最好从那个任务/协程创建一个新的协程。如果你想让一个协程等待另一个协程传输一些数据,我建议使用通道,而不是Deferred对象的返回值。使用通道并根据需要创建尽可能多的协程,是更好的方式IMO