如何命名此Thread
?
override val t: Thread = Thread {
try {
transmit()
} catch (e: Exception) {
println("Transmitter throws exception: $e")
}
}
答案 0 :(得分:8)
您可以使用stdlib中的thread
函数创建命名线程:
fun thread(
start: Boolean = true,
isDaemon: Boolean = false,
contextClassLoader: ClassLoader? = null,
name: String? = null,
priority: Int = -1,
block: () -> Unit
): Thread
只需更改您的代码:
override val t: Thread = thread(name = "transmitter thread") {
try {
transmit()
} catch (e: Exception) {
println("Transmitter throws exception: $e")
}
}
为了在线程中设置线程的名称,您不能使用Thread
的接收Runnable
的构造函数。您需要使用对象表达式对Thread
类进行子类化:
val thread = object : Thread() {
override fun run() {
name = "thread with random name: ${Math.random()}"
}
}
答案 1 :(得分:2)
你可以使用Thread的构造函数,虽然由于它的参数是如何排序的,你必须这样做:
0