How to initialize a Thread in Kotlin?

后端 未结 9 2259
青春惊慌失措
青春惊慌失措 2021-02-06 21:14

In Java it works by accepting an object which implements runnable :

Thread myThread = new Thread(new myRunnable())

where myRunnable

相关标签:
9条回答
  • 2021-02-06 21:48

    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.

    Usually application will wait until all non-daemon threads terminate.

    0 讨论(0)
  • 2021-02-06 21:53

    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.

    0 讨论(0)
  • 2021-02-06 21:58

    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()
    }
    
    0 讨论(0)
  • 2021-02-06 22:01

    Please try this code:

    Thread().run { Thread.sleep(3000); }
    
    0 讨论(0)
  • 2021-02-06 22:07

    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()}")
        }
    
    0 讨论(0)
  • 2021-02-06 22:08

    I did the following and it appears to be working as expected.

    Thread(Runnable {
                //some method here
            }).start()
    
    0 讨论(0)
提交回复
热议问题