如何命名一个线程?
我怎样才能命名这个Thread
?
override val t: Thread = Thread { try { transmit() } catch (e: Exception) { println("Transmitter throws exception: $e") } }
您可以使用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
。 您需要使用对象expression式来对Thread
类进行子类化:
val thread = object : Thread() { override fun run() { name = "thread with random name: ${Math.random()}" } }
你可以使用Thread的构造函数,尽管由于它的参数是如何排序的,你必须这样做:
override val t: Thread = Thread({ try { transmit() } catch (e: Exception) { println("Transmitter throws exception: $e") }}, "Your name here") }