2학년 2학기/모바일 소프트웨어 - 코틀린
Coroutine(1)
by print_soo
2024. 10. 13.
import kotlinx.coroutines.*
import java.lang.Thread.sleep
/*
*
*fun main(){
GlobalScope.launch {
println("Hello world!2") //코루틴에서 실행
}
println("Hello world!1") //main thread에서 실행
sleep(1000)
}
* Hello world!1
* Hello world!2
*
*fun main(){
runBlocking {
launch { //얌체 - 양보하지 않는다.
println("Hello world!2") //코루틴에서 실행
}
}
println("Hello world!1") //main thread에서 실행
}
* Hello world!2
* Hello world!1
*
*fun main(){
val job: Job = CoroutineScope(Dispatchers.Default).launch {
printTask()
}
println(job.isActive)
println("Hello world!2")
sleep(1000)
println(job.isCompleted)
}
suspend fun printTask(){
println("Hello world!1")
delay(1000)
}
*
*
* fun main(){
val str1: Deferred<String> = GlobalScope.async {
"Hello"
}
val str2: Deferred<String> = GlobalScope.async {
" world!"
}
GlobalScope.launch {
print(str1.await())
print(str2.await())
}
sleep(2000)
}
*
* fun main(){
GlobalScope.launch {
doAsyncTask()
}
sleep(1000)
}
suspend fun doAsyncTask() = coroutineScope {
async {
print("Hello, ")
}
async {
print("world!")
}
}
*
*
*suspend fun main(){
val job: Job = GlobalScope.launch {
println("코루틴 - ${Thread.currentThread().name}")
println("world!")
}
println("메인 - ${Thread.currentThread().name}")
println("Hello, ")
job.join() //메인과 이어줄려면 메인도 suspend 처리 해야함.
job.cancel()
}
*
*
*
* */
fun main(){
GlobalScope.launch {
doConcurrentTask()
}
sleep(2000)
println("Main thread ends...")
}
suspend fun doConcurrentTask() = coroutineScope {
launch{
println("coroutine-1 starts")
for (i in 1..5){
println("working ... $i in cocoroutine-1")
delay(100)
}
println("coroutine-1 ends")
}
launch{
println("coroutine-2 starts")
for (i in 1..5){
println("working ... $i in cocoroutine-1")
delay(120)
}
println("coroutine-2 ends")
}
}