How to initialize a Thread in Kotlin?

后端 未结 9 2262
青春惊慌失措
青春惊慌失措 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 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()}")
        }
    

提交回复
热议问题