Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a Thread in Kotlin?

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 
like image 927
Shubhranshu Jain Avatar asked Sep 30 '17 17:09

Shubhranshu Jain


People also ask

How do you initialize a thread?

There are mainly Three ways to create a new thread: (1) By implementing Runnable interface in your class. (2) By extending Thread class. (3) By using inner class.

Is Kotlin single threaded?

The current version of kotlinx. coroutines , which can be used for iOS, supports usage only in a single thread. You cannot send work to other threads by changing a dispatcher. For Kotlin 1.7.


2 Answers

Kotlin comes with a standard library function thread, which I'd recommend to use here:

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

You can use it like this:

thread {     Thread.sleep(1000)     println("test") } 

It has many optional parameters for e.g. not starting the thread directly by setting start to false.


Alternatives

To initialize an instance of class Thread, invoke its constructor:

val t = Thread() 

You may also pass an optional Runnable as a lambda (SAM Conversion) as follows:

Thread {     Thread.sleep(1000)     println("test") } 

The more explicit version would be passing an anonymous implementation of Runnable like this:

Thread(Runnable {     Thread.sleep(1000)     println("test") }) 

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 invoke start() explicitly.

like image 166
s1m0nw1 Avatar answered Oct 04 '22 15:10

s1m0nw1


Runnable:

val myRunnable = runnable {  } 

Thread:

Thread({   // call runnable here   println("running from lambda: ${Thread.currentThread()}") }).start() 

You don't see a Runnable here: in Kotlin it can easily be replaced with a lambda expression. Is there a better way? Sure! Here's how you can instantiate and start a thread Kotlin-style:

thread(start = true) {         println("running from thread(): ${Thread.currentThread()}")     } 
like image 45
Rajesh Dalsaniya Avatar answered Oct 04 '22 15:10

Rajesh Dalsaniya