Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name a thread?

Tags:

kotlin

How can I name this Thread?

    override val t: Thread = Thread {
        try {
            transmit()
        } catch (e: Exception) {
            println("Transmitter throws exception: $e")
        }
    }
like image 211
ycomp Avatar asked Dec 18 '25 21:12

ycomp


2 Answers

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()}"
  }
}
like image 74
Yoav Sternberg Avatar answered Dec 20 '25 12:12

Yoav Sternberg


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")
}
like image 21
MinteZ Avatar answered Dec 20 '25 11:12

MinteZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!