Differentiating Thread and Coroutine (launch & runBlocking) in Kotlin

With the advent of Coroutine, many wonder what’s the different between Thread and Coroutine. Instead of explaining through text, looking at codes execution might helps ease the understanding a little.

Check out each code experiments below, it might clarify things…

Experimenting Thread

Executing Thread with run()

Thread {
println("-Thread--- start : ${getThreadName()}")
Thread.sleep(1000)
println("-Thread--- ended : ${getThreadName()}")
}.run()

run {
println("-Run------ start : ${getThreadName()}")
Thread.sleep(200)
println("-Run------ ended : ${getThreadName()}")
}

Result:

-Thread--- start : main
-Thread--- ended : main
-Run------ start : main
-Run------ ended : main

Calling Thread.run() for a Thread isn’t do anything other than like a normal run on the same thread (i.e. main thread in this case). The code get run synchronously in a sequential manner. (i.e. code run per the order of the line)

Executing Thread with start()

Thread {
println("-Thread--- start : ${getThreadName()}")
Thread.sleep(1000)
println("-Thread--- ended …

--

--