Introduces coroutines in Kotlin. Use an example to show the basic use of coroutines.

  • IntelliJ IDEA 2021.2.2 (Community Edition)
  • Kotlin: 212-1.5.10 – release – IJ5284.40

The first example

New construction

We are using the community edition of IntelliJ IDEA 2021.2.2. Create a new Kotlin project for testing.

The introduction of coroutines

The project is managed using Gradle and we find coroutine dependencies on Github.

dependencies {
    implementation("Org. Jetbrains. Kotlinx: kotlinx coroutines -- core: 1.5.2." ")}Copy the code

Modify the Gradle configuration for the project. Add dependencies to it.

Code sample

Create a class and write the coroutine code in the main method.

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

fun main(a) {
    GlobalScope.launch { // Start a new coroutine in the background and continue
        delay(300)       // Wait 300 milliseconds
        "rustfisher.com".forEach {
            print(it)
            delay(200)   // Wait every time you print
        }
    }
    println("RustFisher")
    Thread.sleep(3000) // block the main thread to prevent exiting too quickly
}
Copy the code

Code run result

In essence, coroutines are lightweight threads.

We started a new coroutine with GlobalScope, which means that the life cycle of the new coroutine is limited only by the life cycle of the entire application.

Globalscope.launch {… } is replaced by thread {…… }, and delay(……) Replace with Thread. Sleep (…) To the same end. Note the import package kotlin.concurrent.thread

Coroutines instead of threads

import java.lang.Thread.sleep
import kotlin.concurrent.thread

fun main(a) {
    thread {
        sleep(300)
        "rustfisher.com".forEach {
            print(it)
            sleep(200)
        }
    }
    println("RustFisher")
    sleep(3000) // block the main thread to prevent exiting too quickly
}
Copy the code

The compiler raises an error if thread{} contains delay

Suspend function ‘delay’ should be called only from a coroutine or another suspend function

Because delay is a special suspend function, it does not block threads, but it suspends coroutines and can only be used in coroutines.

At this point, the first coroutine example is summarized

  • Gradle introduces coroutineskotlinx-coroutines-core
  • GlobalScope.launchStart the coroutines
  • Coroutines inhangfunctiondelay(long)Delay can be achieved, and it can only be used in coroutines

The thread in which the coroutine resides

Coroutines are essentially lightweight threads. Let’s look at the thread information on which the coroutine is located.

Observing thread information

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.lang.Thread.sleep

fun main(a) {
    println("Main Thread information${Thread.currentThread().id}")
    for (i in 1.3.) { // start coroutines several times
        GlobalScope.launch {
            println("Coroutine start #$iThread ID:${Thread.currentThread().id}")
        }
    }
    sleep(2000) // block the main thread to prevent exiting too quickly
    println("End of RustFisher example")}Copy the code

Run log as follows

Main Thread information 1 Id of the thread where the coroutine starts #1:11 ID of the thread where the coroutine starts #3:14 ID of the thread where the coroutine starts #2:13 RustFisher Example EndCopy the code

You can see that the coroutines are started multiple times, and they don’t have to be in the same thread. That is, there is the possibility of being on the same thread.

Try frantically starting coroutines, increasing the number of loops for (I in 1.. 3000). If you look at the log, you can see that there are duplicate thread ids.