coroutine demo

This commit is contained in:
Alexander Nozik 2021-03-05 10:54:18 +03:00
parent 35b9fc62f3
commit ddfd17de81
2 changed files with 44 additions and 3 deletions

View File

@ -1,5 +1,3 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.4.30"
}
@ -7,20 +5,27 @@ plugins {
group = "ru.mipt.npm"
version = "1.0"
// Where to get dependencies
repositories {
mavenCentral()
}
dependencies {
//loading coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3")
//testing libraries
testImplementation(kotlin("test-junit5"))
testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.6.0")
}
// Load testing platform
tasks.test {
useJUnitPlatform()
}
tasks.withType<KotlinCompile>() {
// Set a byte-code target for JVM
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions.jvmTarget = "11"
}

View File

@ -0,0 +1,36 @@
package demos
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
suspend fun doASuspendedThing() {
delay(500)
}
suspend fun doASuspendedThingWithResult(): Int {
delay(500)
return 4
}
suspend fun main() {
//sequential coroutine
GlobalScope.launch {
doASuspendedThingWithResult()
// do a thing and do next thing when the result is there without blocking
doASuspendedThing()
}
//parallel coroutines
GlobalScope.launch(Dispatchers.Default) {
val job1 = launch {
doASuspendedThing()
}
val job2 = launch {
doASuspendedThing()
}
job1.join()
job2.join()
}
}