How to initialize a Thread in Kotlin?

Kotlin comes with a standard library function thread, which I’d recommend to use here:

public fun thread(
    start: Boolean = true, 
    isDaemon: Boolean = false, 
    contextClassLoader: ClassLoader? = null, 
    name: String? = null, 
    priority: Int = -1, 
    block: () -> Unit): Thread

You can use it like this:

thread {
    Thread.sleep(1000)
    println("test")
}

It has many optional parameters for e.g. not starting the thread directly by setting start to false.


Alternatives

To initialize an instance of class Thread, invoke its constructor:

val t = Thread()

You may also pass an optional Runnable as a lambda (SAM Conversion) as follows:

Thread {
    Thread.sleep(1000)
    println("test")
}

The more explicit version would be passing an anonymous implementation of Runnable like this:

Thread(Runnable {
    Thread.sleep(1000)
    println("test")
})

Note that the previously shown examples do only create an instance of a Thread but don’t actually start it. In order to achieve that, you need to invoke start() explicitly.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)