Erik Dreyer
09/04/2021, 8:42 PMErik Dreyer
09/04/2021, 8:45 PMstreetsofboston
09/04/2021, 10:18 PM.join()
in the Java code, guaranteed a "first" then a "second", change the calls to launch
to calls to withContext
.Scott Whitman
09/06/2021, 2:38 PMpublic fun main() {
withContextSolution()
asyncSolution()
}
public fun withContextSolution(): Unit = runBlocking {
println("\n***** withContext *****")
val startTime = System.currentTimeMillis()
val ctx1 = newSingleThreadContext("first")
val ctx2 = newSingleThreadContext("second")
(1..10).forEach {
withContext(ctx1) {
delay(1000)
if (it % 2 == 1) println("$it ${Thread.currentThread().name}")
}
withContext(ctx2) {
delay(1000)
if (it % 2 == 0) println("$it ${Thread.currentThread().name}")
}
}
println("Elapsed Time: ${System.currentTimeMillis() - startTime}")
}
public fun asyncSolution(): Unit = runBlocking {
println("\n***** async / await *****")
val startTime = System.currentTimeMillis()
val ctx1 = newSingleThreadContext("first")
val ctx2 = newSingleThreadContext("second")
(1..10).forEach {
val first = async(ctx1) {
delay(1000)
if (it % 2 == 1) println("$it ${Thread.currentThread().name}")
}
val second = async(ctx2) {
delay(1000)
if (it % 2 == 0) println("$it ${Thread.currentThread().name}")
}
first.await()
second.await()
}
println("Elapsed Time: ${System.currentTimeMillis() - startTime}")
}