Implementing Threads in Kotlin?

Threads represent concurrent activity in Kotlin. The simplest way of implementing threads is by extending the Thread class. The code for the thread is defined in the run method. Here is a thread that executes two loops counting from 1 to 10.

class MyThread: Thread() {

    override fun run() {

        var i:Int

        for(i in 1..10)

        {

            println(i)

            Thread.sleep(1000)

        }

    }

}

fun main(args: Array<String>)

{

    var m1:MyThread=MyThread()

    var m2:MyThread=MyThread()

    m1.start()

    m2.start()


}

Varanasi Software Junction: Kotlin Threads

The call to the start method starts the thread execution and the output proves that they are running concurrently.
What happens if I call the run method instead.

class MyThread: Thread() {
    override fun run() {
        var i:Int
        for(i in 1..10)
        {
            println(i)
            Thread.sleep(1000)
        }
    }
}
fun main(args: Array<String>)
{
    var m1:MyThread=MyThread()
    var m2:MyThread=MyThread()
    m1.run()
    m2.run()

}

Varanasi Software Junction: Kotlin Threads

Threads can also be created by implementing the Runnable interface.

class MyThread: Runnable {
    override fun run() {
        var i:Int
        for(i in 1..10)
        {
            println(i)
            Thread.sleep(1000)
        }
    }
}
fun main(args: Array<String>)
{
    var m1:Thread= Thread(MyThread())
    var m2:Thread=Thread(MyThread())
    m1.start()
    m2.start()

}


Varanasi Software Junction: Kotlin Threads

Kotlin comes with an inbuilt method called thread that can be used directly to run a thread.


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


Its class is import kotlin.concurrent.thread which will have to be imported.


Here is a code sample that counts from 1 to 10.

import kotlin.concurrent.thread


fun main(args: Array<String>) {

thread{var i:Int=0

for(i in 1..10)

{

    println(i)

    Thread.sleep(1000)

}

}


    thread{var i:Int=0

        for(i in 1..10)

        {

            println(i)

            Thread.sleep(1000)

        }

    }

}


Varanasi Software Junction: Kotlin Threads



Another way of implementing a Thread



fun main(args: Array<String>) {

Thread({

var i:Int=0

for(i in 1..10)

{

println(i)

Thread.sleep(1000)

}

}).start()


    Thread({

        var i:Int=0

        for(i in 1..10)

        {

            println(i)

            Thread.sleep(1000)

        }

    }).start()

}







End

Post a Comment

0 Comments