How can I name this Thread?
override val t: Thread = Thread {
try {
transmit()
} catch (e: Exception) {
println("Transmitter throws exception: $e")
}
}
You can create a named thread using the thread function from stdlib:
fun thread(
start: Boolean = true,
isDaemon: Boolean = false,
contextClassLoader: ClassLoader? = null,
name: String? = null,
priority: Int = -1,
block: () -> Unit
): Thread
Just change your code:
override val t: Thread = thread(name = "transmitter thread") {
try {
transmit()
} catch (e: Exception) {
println("Transmitter throws exception: $e")
}
}
In order to set the thread's name from within the thread, you can't use Thread's constructor that receives Runnable. You need to subclass the Thread class using the object expression:
val thread = object : Thread() {
override fun run() {
name = "thread with random name: ${Math.random()}"
}
}
You can use Thread's constructor, although due to how its arguments are ordered, you'll have to do this:
override val t: Thread = Thread({
try {
transmit()
} catch (e: Exception) {
println("Transmitter throws exception: $e")
}}, "Your name here")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With