In Java it works by accepting an object which implements runnable :
Thread myThread = new Thread(new myRunnable())
where myRunnable
is a class implementing Runnable
.
But when I tried this in Kotlin, it doesn't seems to work:
var myThread:Thread = myRunnable:Runnable
Best way would be to use
thread()
generator function fromkotlin.concurrent
: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.concurrent/thread.htmlYou should check its default values, as they're quite useful:
Note that you don't need to call
start()
like in the Thread example, or providestart=true
.Be careful with threads that run for a long period of time. It's useful to specify
thread(isDaemon= true)
so your application would be able to terminate correctly.Basic example of
Thread
withLamda
Please try this code:
For initialising an object of
Thread
you simply invoke the constructor:Then, you can also pass an optional
Runnable
with a lambda (SAM Conversion) like this:The more explicit version is passing an anonymous implementation of
Runnable
like this: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 invokestart()
explicitly.Last but not least, you need to know the standard library function
thread
, which I'd recommend to use:You can use it like this:
It has many optional parameters for e.g. directly starting the thread as shown here. Note that
true
is the default value ofstart
anyway.Firstly, create a function for set default propery
then perform background operation calling this function
Or kotlin coroutines also can be used to perform background task