Creating and Running Kotlin Threads

There are four ways to implement threads in Kotlin.

Implementing by inheriting the Thread class

The following example implements a thread by inheriting a class.

class ThreadExtends : Thread(){
    override fun run() {
        println("Hello! This is extends ${currentThread()}")
    }
}

fun main() {
    val thread = ThreadExtends()
    thread.start()
}

Output:

Hello! This is extends Thread[Thread-0,5,main]

Implementing by inheriting the Runnable interface

The following example implements the Runnable interface.

class ThreadRunnable : Runnable {
    override fun run() {
        println("Hello! This is runnable ${hashCode()}")
    }
}

fun main() {
    val thread = Thread(ThreadRunnable())

    thread.start()
}

Output:

Hello! This is runnable 109369515

Implementing with an anonymous object

The following example uses an anonymous object.

fun main() {
    val thread = object : Thread() {
        override fun run() {
            println("Hello! This is object Thread ${currentThread()}")
        }
    }

    thread.start()
}

Output:

Hello! This is object Thread Thread[Thread-0,5,main]

Implementing with a lambda expression

The following example uses a lambda expression.

fun main() {
    var thread = Thread {
        println("Hello! This is lambda thread ${Thread.currentThread()}")
    }

    thread.start()
}

Output:

Hello! This is lambda thread Thread[Thread-0,5,main]

You can also create an object with a lambda expression and implement a function that adds behavior, as shown below.

fun startThread(): Thread {
    val thread = Thread {
        println("Hello! This is start lambda thread ${Thread.currentThread()}")
    }
    thread.start()
    return thread;
}

fun main() {
    startThread()
}

Output:

Hello! This is start lambda thread Thread[Thread-0,5,main]