Interrupting a thread

Report a typo

You are dealing with the class Worker that extends Thread. The class overrides the function run to do something useful.

class Worker : Thread() {
    override fun run() {
        try {
            sleep(1000L)
        } catch (e: InterruptedException) {
            throw RuntimeException("You need to wait longer!", e)
        }
        val currentId = currentThread().id
        if (currentId == mainThreadId) {
            throw RuntimeException("You must start a new thread!")
        }
        while (true) {
            if (isInterrupted) {
                println("Interrupted")
                break
            }
        }
    }
}

You need to start an instance of this class in a new thread, wait for it a little (2000-3000 milliseconds), and interrupt this new thread.

If you do not interrupt the thread after starting, something bad will happen.

Write a program in Kotlin
import java.lang.Thread.sleep
val mainThreadId = Thread.currentThread().id

fun main() {
val worker = Worker()

// write your code here
}

// Don't change the code below
class Worker : Thread() {
override fun run() {
try {
sleep(1000L)
} catch (e: InterruptedException) {
throw RuntimeException("You need to wait longer!", e)
}
val currentId = currentThread().id
if (currentId == mainThreadId) {
throw RuntimeException("You must start a new thread!")
}
while (true) {
if (isInterrupted) {
println("Interrupted")
break
}
}
}
}
___

Create a free account to access the full topic