How to fix the code

Report a typo

Consider the following code with two threads: the main thread and one worker thread.

Both threads work with the same variable done. Sometimes they may not be able to see changes of the variable.

Choose the correct way to fix the code.

import java.util.concurrent.TimeUnit

fun main() {
    val runnable = ThreadSafe1()
    
    Thread(runnable).start()

    TimeUnit.SECONDS.sleep(5)

    runnable.cancel()
}

class ThreadSafe1: Runnable {
    var done: Boolean = false // sometimes changes are not visible

    override fun run() {
        while (!done) {
            println("Running")
        }
        println("Done")
    }

    fun cancel() {
        done = true
    }
}
Select one option from the list
___

Create a free account to access the full topic