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