如何命名线程?

时间:2017-04-01 06:06:10

标签: kotlin

如何命名此Thread

    override val t: Thread = Thread {
        try {
            transmit()
        } catch (e: Exception) {
            println("Transmitter throws exception: $e")
        }
    }

2 个答案:

答案 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