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()
}
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)
}
}
}
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
0 Comments