Last active
October 26, 2018 10:21
-
-
Save mayojava/75ce706e880536928202f207b3d59910 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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