윤동환
09/06/2023, 8:21 AMsuspend fun service(): String = coroutineScope {
launch(Dispatchers.Default) { getOrder() }
launch(<http://Dispatchers.IO|Dispatchers.IO>) { getProduct() }
println("this = ${coroutineContext.job}")
"service"
}
suspend fun getOrder(): String {
<http://logger.info|logger.info> { "get ordering!!! [Order Thread(${Thread.currentThread().id}) : ${Thread.currentThread().name}]" }
var no = 10
while (true) {
if (no == 20) break
no++
<http://logger.info|logger.info> { "$no [Order Thread(${Thread.currentThread().id}) : ${Thread.currentThread().name}]" }
delay(700)
}
return "order"
}
suspend fun getProduct(): String {
<http://logger.info|logger.info> { "get product!!! [Product Thread(${Thread.currentThread().id}) : ${Thread.currentThread().name}]" }
var no = 10
while (true) {
if (no == 20) break
no++
<http://logger.info|logger.info> { "$no [Product Thread(${Thread.currentThread().id}) : ${Thread.currentThread().name}]" }
delay(300)
}
return "product"
}
private val logger = KotlinLogging.logger {}
I have a question about running coroutines by Dispatchers. On this code, i launched two suspendable functions at service function, getOrder func launched by Dispatchers.Default but the next one getProduct is by Dispatchers.IO.
But when this simple program finished, the log message like that. All coroutines has launched by Dispatchers.Default.
Why coroutines that resuming getProduct functions has running on Dispatchers.Default not Dispatchers.IO?
17:17:19.713 [DefaultDispatcher-worker-1 @coroutine#1] INFO m.y.h.study.Study4 - get ordering!!! [Order Thread(14) : DefaultDispatcher-worker-1 @coroutine#1]
17:17:19.713 [DefaultDispatcher-worker-2 @coroutine#2] INFO m.y.h.study.Study4 - get product!!! [Product Thread(15) : DefaultDispatcher-worker-2 @coroutine#2]
17:17:19.714 [DefaultDispatcher-worker-1 @coroutine#1] INFO m.y.h.study.Study4 - 11 [Order Thread(14) : DefaultDispatcher-worker-1 @coroutine#1]
17:17:19.714 [DefaultDispatcher-worker-2 @coroutine#2] INFO m.y.h.study.Study4 - 11 [Product Thread(15) : DefaultDispatcher-worker-2 @coroutine#2]
17:17:20.019 [DefaultDispatcher-worker-1 @coroutine#2] INFO m.y.h.study.Study4 - 12 [Product Thread(14) : DefaultDispatcher-worker-1 @coroutine#2]
...
Sam
09/06/2023, 8:24 AMSam
09/06/2023, 8:26 AMSam
09/06/2023, 8:31 AMcoroutineContext[CoroutineDispatcher]
instead of the thread name if you want to see the actual dispatcher.윤동환
09/06/2023, 9:10 AMSam
09/06/2023, 9:22 AM윤동환
09/06/2023, 10:14 AMSzymon Jeziorski
09/06/2023, 12:14 PM