Last active
March 4, 2022 00:18
-
-
Save edreyer/e3ac7fbdd6146806b3839d79262f63bd to your computer and use it in GitHub Desktop.
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
import kotlinx.coroutines.launch | |
import kotlinx.coroutines.newSingleThreadContext | |
import kotlinx.coroutines.runBlocking | |
// inspired by: https://dzone.com/articles/print-even-and-odd-numbers-using-two-threads-compl | |
// You can run this in a Kotlin REPL | |
fun main() = runBlocking { | |
(1..100).forEach { | |
val first = async(newSingleThreadContext("first")) { | |
if (it % 2 == 1) println("$it ${Thread.currentThread().name}") | |
} | |
val second = async(newSingleThreadContext("second")) { | |
if (it % 2 == 0) println("$it ${Thread.currentThread().name}") | |
} | |
first.await() | |
second.await() | |
} | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment