kotlin приоритет сопрограмм исполнения - PullRequest
1 голос
/ 24 апреля 2020

Мне нужна помощь в понимании результатов следующих 2 частей кода

1-й фрагмент

fun main() = runBlocking { 
    launch {
        println("Task from runBlocking")
    }

    coroutineScope { 
        launch {
            println("Task from nested launch")
        }

        println("Task from coroutine scope")
    }

    println("Coroutine scope is over")
}

И, 2-й фрагмент

fun main() = runBlocking { 
    launch {
        println("Task from runBlocking")
    }

    println("Coroutine scope is over") 
}

Результат 1-го фрагмента:

Task from coroutine scope
Task from runBlocking
Task from nested launch
Coroutine scope is over

Результат 2-го фрагмента:

Coroutine scope is over
Task from runBlocking

Итак, вопрос в том, почему утверждения печатались в таком порядке?

1 Ответ

0 голосов
/ 05 мая 2020

Для 1st snippet вы используете coroutineScope, который, как вы можете видеть из документации , определяется как функция suspend, поэтому он блокирует текущий поток, а "Coroutine scope is over" не печатается до завершения блока coroutineScope.

Для 2nd snippet строка "Coroutine scope is over" печатается до "Task from run blocking", потому что ее println выполняется в главном потоке, а launch - в рабочем. поток еще не закончил свою работу.

fun mainOne() = runBlocking {
  launch {
      println("Task from runBlocking")
  }

  // coroutineScope is defined as a suspend function, so it's blocking the current thread
  coroutineScope {

      launch {
          // worker thread, slower than main thread, printed after "Task from coroutine scope"
          println("Task from nested launch")
      }
      // main thread, printed before "Task from nested launch" within CoroutineScope
      println("Task from coroutine scope")
  }

  // main thread is now free to run and it prints the string below
  println("Coroutine scope is over")
}


fun mainTwo() = runBlocking {
    launch {
        // worker thread, slower than main thread, printed after "Coroutine scope is over" due to concurrency
        println("Task from runBlocking")
    }
    // main thread is running and prints the string below before launch job has finished.
    // If you put a delay here you'll notice that launch job gets completed before "Coroutine scope is over"
    // E.g delay(2000)
    println("Coroutine scope is over")
}

Надеюсь, это имеет смысл:)

...