From c03ae2234dc6ed7ade9c3ae94cffb59194282484 Mon Sep 17 00:00:00 2001 From: jesperancinha Date: Sun, 17 Mar 2024 10:04:36 +0100 Subject: [PATCH] A better and more complete example --- .../jesperancinha/ktd/SimpleConcurrency.kt | 39 +++++++++++++------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/jeorg-kotlin-coroutines/coroutines-crums-group-1/src/main/kotlin/org/jesperancinha/ktd/SimpleConcurrency.kt b/jeorg-kotlin-coroutines/coroutines-crums-group-1/src/main/kotlin/org/jesperancinha/ktd/SimpleConcurrency.kt index 7879cee1c..032c4c6bd 100644 --- a/jeorg-kotlin-coroutines/coroutines-crums-group-1/src/main/kotlin/org/jesperancinha/ktd/SimpleConcurrency.kt +++ b/jeorg-kotlin-coroutines/coroutines-crums-group-1/src/main/kotlin/org/jesperancinha/ktd/SimpleConcurrency.kt @@ -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 = emptyArray()) = runBlocking{ - val coroutine1 = async { - delay(Duration.ofMillis(nextLong(500))) - println("Coroutine 1 is complete!") + fun main(args: Array = 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") } } }