Skip to content

Instantly share code, notes, and snippets.

@edreyer
Last active March 4, 2022 00:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save edreyer/e3ac7fbdd6146806b3839d79262f63bd to your computer and use it in GitHub Desktop.
Save edreyer/e3ac7fbdd6146806b3839d79262f63bd to your computer and use it in GitHub Desktop.
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