funmain() = runBlocking<Unit> { val time = measureTimeMillis { val one = doSomethingUsefulOne() val two = doSomethingUsefulTwo() println("The answer is ${one + two}") } println("Completed in $time ms") }
suspendfundoSomethingUsefulOne(): Int { delay(1000L) // 假设我们在这里做了些有用的事 return13 }
suspendfundoSomethingUsefulTwo(): Int { delay(1000L) // 假设我们在这里也做了一些有用的事 return29 }
funmain() = 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") }
suspendfundoSomethingUsefulOne(): Int { delay(1000L) // 假设我们在这里做了些有用的事 return13 }
suspendfundoSomethingUsefulTwo(): Int { delay(1000L) // 假设我们在这里也做了些有用的事 return29 }
funmain() = runBlocking<Unit> { launch { // 运行在父协程的上下文中,即 runBlocking 主协程 println("main runBlocking : I'm working in thread ${Thread.currentThread().name}") } launch(Dispatchers.Unconfined) { // 不受限的——将工作在主线程中 println("Unconfined : I'm working in thread ${Thread.currentThread().name}") } launch(Dispatchers.Default) { // 将会获取默认调度器 println("Default : I'm working in thread ${Thread.currentThread().name}") } launch(newSingleThreadContext("MyOwnThread")) { // 将使它获得一个新的线程 println("newSingleThreadContext: I'm working in thread ${Thread.currentThread().name}") } }
/** 输出 注意先后顺序 Unconfined : I'm working in thread main @coroutine#3 Default : I'm working in thread DefaultDispatcher-worker-1 @coroutine#4 main runBlocking : I'm working in thread main @coroutine#2 newSingleThreadContext: I'm working in thread MyOwnThread @coroutine#5 **/