funmain() = runBlocking<Unit> { //sampleStart val time = measureTimeMillis { val one = doSomethingUsefulOne() val two = doSomethingUsefulTwo() println("The answer is ${one + two}") } println("Completed in $time ms") //sampleEnd }
suspendfundoSomethingUsefulOne(): Int { delay(1000L) // pretend we are doing something useful here return13 }
suspendfundoSomethingUsefulTwo(): Int { delay(1000L) // pretend we are doing something useful here, too return29 }
suspend fun failedConcurrentSum(): Int = coroutineScope { val one = async<Int> { try { delay(Long.MAX_VALUE) // Emulates very long computation 42 } finally { println("First child was cancelled") } } val two = async<Int> { println("Second child throws an exception") throw ArithmeticException() } one.await() + two.await() } 这样,如果 ```concurrentSum()``` 函数发生错误并引发异常,则在其作用域中启动的所有协程都将被取消