Skip to content

Commit

Permalink
A better and more complete example
Browse files Browse the repository at this point in the history
  • Loading branch information
jesperancinha committed Mar 17, 2024
1 parent aaef658 commit c03ae22
Showing 1 changed file with 27 additions and 12 deletions.
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")
}
}
}

0 comments on commit c03ae22

Please sign in to comment.