Skip to content

Instantly share code, notes, and snippets.

@mayojava
Last active October 26, 2018 10:21
Show Gist options
  • Save mayojava/75ce706e880536928202f207b3d59910 to your computer and use it in GitHub Desktop.
Save mayojava/75ce706e880536928202f207b3d59910 to your computer and use it in GitHub Desktop.
fun main() = runBlocking {
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (i < 5) { // computation loop, just wastes CPU
// print a message twice a second
if (System.currentTimeMillis() >= nextPrintTime) {
println("I'm sleeping ${i++} ...")
nextPrintTime += 500L
}
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancelAndJoin() // cancels the job and waits for its completion
println("main: Now I can quit.")
}
//console output
I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
main: I'm tired of waiting!
I'm sleeping 3 ...
I'm sleeping 4 ...
main: Now I can quit.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment