How to initialize a Thread in Kotlin?

后端 未结 9 2250
青春惊慌失措
青春惊慌失措 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.

提交回复
热议问题