fun main(args : Array<String>) = runBlocking{
val time = measureTimeMillis {
val one = doSomethingUsefulOne()
val two = doSomethingUsefulTwo()
println("The answer is ${one + two}")
}
println("Completed in $time ms ")
}
suspend fun doSomethingUsefulOne() : Int{
delay(1000L)
return 13
}
suspend fun doSomethingUsefulTwo() : Int{
delay(1000L)
return 29
}
launch와 async의 차이점은 반환값이다. (launch = job / async = deferred)
fun main(args : Array<String>) = runBlocking{
val time = measureTimeMillis {
val one = async {
doSomethingUsefulOne()
}
val two = async {
doSomethingUsefulTwo()
}
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
}
첫 번째 방법보다 시간이 1초 앞 당겨진 것을 확인할 수 있다.
fun main(args : Array<String>) = runBlocking{
val time = measureTimeMillis {
val one = async(start = CoroutineStart.LAZY) {
doSomethingUsefulOne()
}
val two = async(start = CoroutineStart.LAZY) {
doSomethingUsefulTwo()
}
one.start()
two.start()
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
}
await() 함수만 사용한 경우, Sequential by default와 비슷한 결과를 확인할 수 있다.
지연 시작을 왜 사용할까?? 🤔
fun main(args : Array<String>) = runBlocking<Unit>{
val time = measureTimeMillis {
try {
failedConcurrentSum()
//val one = somethingUsefulOneAsync()
//val two = somethingUsefulTwoAsync()
one.start()
two.start()
println("The answer is ${one.await() + two.await()}")
} catch (e: ArithmeticException) {
println("Computation failed with ArithmeticException")
}
}
println("Time : $time ms...")
}
suspend fun failedConcurrentSum() : Int = coroutineScope {
val one = async<Int> {
try{
delay(Long.MAX_VALUE)
42
}finally {
println("First child was cancelled")
}
}
val two = async<Int> {
println("Second child throws an exception")
throw ArithmeticException()
}
one.await() + two.await()
}
fun main(args : Array<String>) = runBlocking<Unit>{
val time = measureTimeMillis {
try {
//failedConcurrentSum()
val one = somethingUsefulOneAsync()
val two = somethingUsefulTwoAsync()
one.start()
two.start()
println("The answer is ${one.await() + two.await()}")
} catch (e: ArithmeticException) {
println("Computation failed with ArithmeticException")
}
}
println("Time : $time ms...")
}
suspend fun somethingUsefulOneAsync() = GlobalScope.async {
doSomethingUsefulOne()
}
suspend fun somethingUsefulTwoAsync() = GlobalScope.async {
doSomethingUsefulTwo()
}
suspend fun doSomethingUsefulOne() : Int{
delay(Long.MAX_VALUE)
throw ArithmeticException()
}
suspend fun doSomethingUsefulTwo() : Int{
delay(1000L)
return 29
}