-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
aaef658
commit c03ae22
Showing
1 changed file
with
27 additions
and
12 deletions.
There are no files selected for viewing
39 changes: 27 additions & 12 deletions
39
...tines/coroutines-crums-group-1/src/main/kotlin/org/jesperancinha/ktd/SimpleConcurrency.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,42 @@ | ||
package org.jesperancinha.ktd | ||
|
||
import kotlinx.coroutines.async | ||
import kotlinx.coroutines.launch | ||
import kotlinx.coroutines.runBlocking | ||
import kotlinx.coroutines.time.delay | ||
import java.lang.Thread.sleep | ||
import java.time.Duration | ||
import kotlin.random.Random | ||
import kotlin.random.Random.Default.nextLong | ||
import kotlin.system.measureTimeMillis | ||
|
||
class SimpleConcurrency { | ||
companion object { | ||
/** | ||
* This test runs sleep with the purpose to show concurrency in coroutines | ||
*/ | ||
@JvmStatic | ||
fun main(args: Array<String> = emptyArray()) = runBlocking{ | ||
val coroutine1 = async { | ||
delay(Duration.ofMillis(nextLong(500))) | ||
println("Coroutine 1 is complete!") | ||
fun main(args: Array<String> = emptyArray()) = runBlocking { | ||
val timeToRun = measureTimeMillis { | ||
val coroutine1 = async { | ||
delay(Duration.ofMillis(nextLong(100))) | ||
async { | ||
val randomTime = nextLong(500) | ||
sleep(Duration.ofMillis(randomTime)) | ||
println("Coroutine 1 is complete in $randomTime!") | ||
}.await() | ||
} | ||
val coroutine2 = | ||
async { | ||
delay(Duration.ofMillis(nextLong(100))) | ||
async { | ||
val randomTime = nextLong(500) | ||
sleep(Duration.ofMillis(randomTime)) | ||
println("Coroutine 2 is complete in $randomTime!") | ||
}.await() | ||
} | ||
coroutine2.await() | ||
coroutine1.await() | ||
} | ||
val coroutine2 = async { | ||
delay(Duration.ofMillis(nextLong(500))) | ||
println("Coroutine 2 is complete!") | ||
} | ||
coroutine2.await() | ||
coroutine1.await() | ||
println("Time to run is $timeToRun milliseconds") | ||
} | ||
} | ||
} |