@@ -353,12 +353,13 @@ example shows:
353
353
354
354
``` kotlin
355
355
fun main (args : Array <String >) = runBlocking<Unit > {
356
+ val startTime = System .currentTimeMillis()
356
357
val job = launch(CommonPool ) {
357
- var nextPrintTime = System .currentTimeMillis()
358
+ var nextPrintTime = startTime
358
359
var i = 0
359
- while (i < 10 ) { // computation loop
360
- val currentTime = System .currentTimeMillis()
361
- if (currentTime >= nextPrintTime) {
360
+ while (i < 10 ) { // computation loop, just wastes CPU
361
+ // print a message twice a second
362
+ if (System .currentTimeMillis() >= nextPrintTime) {
362
363
println (" I'm sleeping ${i++ } ..." )
363
364
nextPrintTime + = 500L
364
365
}
@@ -393,18 +394,19 @@ There are two approaches to making computation code cancellable. The first one i
393
394
invoke a suspending function. There is a [ yield] function that is a good choice for that purpose.
394
395
The other one is to explicitly check the cancellation status. Let us try the later approach.
395
396
396
- Replace ` while (true ) ` in the previous example with ` while (isActive) ` and rerun it.
397
+ Replace ` while (i < 10 ) ` in the previous example with ` while (isActive) ` and rerun it.
397
398
398
399
``` kotlin
399
400
fun main (args : Array <String >) = runBlocking<Unit > {
401
+ val startTime = System .currentTimeMillis()
400
402
val job = launch(CommonPool ) {
401
- var nextPrintTime = 0L
403
+ var nextPrintTime = startTime
402
404
var i = 0
403
405
while (isActive) { // cancellable computation loop
404
- val currentTime = System .currentTimeMillis()
405
- if (currentTime >= nextPrintTime) {
406
+ // print a message twice a second
407
+ if (System .currentTimeMillis() >= nextPrintTime) {
406
408
println (" I'm sleeping ${i++ } ..." )
407
- nextPrintTime = currentTime + 500L
409
+ nextPrintTime + = 500L
408
410
}
409
411
}
410
412
}
0 commit comments