How to initialize a Thread in Kotlin?

2020-06-30 08:57发布

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

9条回答
劳资没心,怎么记你
2楼-- · 2020-06-30 09:31

Best way would be to use thread() generator function from kotlin.concurrent: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.concurrent/thread.html

You should check its default values, as they're quite useful:

thread() { /* do something */ }

Note that you don't need to call start() like in the Thread example, or provide start=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.

查看更多
Rolldiameter
3楼-- · 2020-06-30 09:35

Basic example of Thread with Lamda

fun main() {
    val mylamda = Thread({
        for (x in 0..10){
            Thread.sleep(200)
            println("$x")
        }
   })
    startThread(mylamda)

}

fun startThread(mylamda: Thread) {
    mylamda.start()
}
查看更多
混吃等死
4楼-- · 2020-06-30 09:35

Please try this code:

Thread().run { Thread.sleep(3000); }
查看更多
Juvenile、少年°
5楼-- · 2020-06-30 09:40

For initialising an object of Thread you simply invoke the constructor:

val t = Thread()

Then, you can also pass an optional Runnable with a lambda (SAM Conversion) like this:

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

The more explicit version is 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.

Last but not least, you need to know the standard library function thread, which I'd recommend to use:

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(start = true) {
    Thread.sleep(1000)
    println("test")
}

It has many optional parameters for e.g. directly starting the thread as shown here. Note that true is the default value of start anyway.

查看更多
来,给爷笑一个
6楼-- · 2020-06-30 09:45
fun main(args: Array<String>) {

    Thread({
        println("test1")
        Thread.sleep(1000)
    }).start()

    val thread = object: Thread(){
        override fun run(){
            println("test2")
            Thread.sleep(2000)
        }
    }

    thread.start()

    Thread.sleep(5000)
}
查看更多
Lonely孤独者°
7楼-- · 2020-06-30 09:46

Firstly, create a function for set default propery

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

then perform background operation calling this function

thread(start = true) {
     //Do background tasks...
}

Or kotlin coroutines also can be used to perform background task

GlobalScope.launch {

    //TODO("do background task...")
    withContext(Dispatchers.Main) {
        // TODO("Update UI")
    }
    //TODO("do background task...")
}
查看更多
登录 后发表回答