funmain() =runBlocking {val job =launch {repeat(1000) { i ->println("job: I'm sleeping $i ...")delay(500L) } }delay(1300L)println("main: I'm tired of waiting!") job.cancel() job.join()println("main: Now I can quit.")}
funmain() =runBlocking {val job =launch {try {repeat(1000) { i ->println("job: I'm sleeping $i ...")delay(500L) } } finally {withContext(NonCancellable) {println("job: I'm running finally")delay(1000L)println("job: And I've just delayed for 1 sec because I'm non-cancellable") } } }delay(1300L)println("main: I'm tired of waiting!") job.cancelAndJoin()println("main: Now I can quit.")}
funmain() =runBlocking {val result =withTimeoutOrNull(1300L) {repeat(10000) { i ->println("I'm sleeping $i ...")delay(500L) }"Done"// will get cancelled before it produces this result }println("Result is $result")}
suspendfundoSomethingOne(): Int {delay(1000L)return13}suspendfundoSomethingTwo(): Int {delay(1000L)return29}funmain() =runBlocking {val time =measureTimeMillis {val one =doSomethingOne()val two =doSomethingTwo()println("The answer is ${one + two}") }println("Completed in $time ms")}
這個時候我們可以使用Coroutine裡面提供的async、await函數來讓兩個函數可以同時執行
val time =measureTimeMillis {val one =async { doSomethingOne() }val two =async { doSomethingTwo() }println("The answer is ${one.await() + two.await()}")}println("Completed in $time ms")