如何在Kotlin中初始化一个线程?

Shu*_*ain 26 java multithreading kotlin

在Java中,它通过接受实现runnable的对象来工作:

Thread myThread = new Thread(new myRunnable())
Run Code Online (Sandbox Code Playgroud)

哪个myRunnable是实现类Runnable.

但是当我在Kotlin尝试这个时,它似乎不起作用:

var myThread:Thread = myRunnable:Runnable
Run Code Online (Sandbox Code Playgroud)

s1m*_*nw1 24

要初始化一个对象,Thread只需调用构造函数:

val t = Thread()
Run Code Online (Sandbox Code Playgroud)

然后,您还可以传递一个Runnable带有lambda(SAM转换)的可选项,如下所示:

Thread {
    Thread.sleep(1000)
    println("test")
}
Run Code Online (Sandbox Code Playgroud)

更明确的版本是传递这样的匿名实现Runnable:

Thread(Runnable {
    Thread.sleep(1000)
    println("test")
})
Run Code Online (Sandbox Code Playgroud)

请注意,先前显示的示例仅创建 a的实例,Thread但实际上并未启动它.为了实现这一点,您需要start()显式调用.

最后但并非最不重要的,你需要知道thread我建议使用的标准库函数:

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

你可以像这样使用它:

thread(start = true) {
    Thread.sleep(1000)
    println("test")
}
Run Code Online (Sandbox Code Playgroud)

它有许多可选参数,例如直接启动线程,如下所示.

  • 请注意,您可以省略 `start = true`(因为默认情况下 `start` 为 `true`),只需编写 `thread { Thread.sleep(1000) }` 即可启动线程。 (2认同)

Ada*_*itz 11

我做了以下操作,它似乎按预期工作。

Thread(Runnable {
            //some method here
        }).start()
Run Code Online (Sandbox Code Playgroud)


Raj*_*iya 7

可运行的:

val myRunnable = runnable {

}
Run Code Online (Sandbox Code Playgroud)

线:

Thread({  
// call runnable here
  println("running from lambda: ${Thread.currentThread()}")
}).start()
Run Code Online (Sandbox Code Playgroud)

您在这里看不到Runnable:在Kotlin中,可以轻松地将其替换为lambda表达式。有没有更好的办法?当然!实例化和启动Kotlin风格的线程的方法如下:

thread(start = true) {  
      println("running from thread(): ${Thread.currentThread()}")
    }
Run Code Online (Sandbox Code Playgroud)


Ale*_*hin 6

最好的方法是使用以下thread()生成器函数kotlin.concurrenthttps : //kotlinlang.org/api/latest/jvm/stdlib/kotlin.concurrent/thread.html

您应该检查其默认值,因为它们非常有用:

thread() { /* do something */ }
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要start()像 Thread 示例中那样调用,也不需要提供start=true.

小心运行很长时间的线程。指定很有用,thread(isDaemon= true)以便您的应用程序能够正确终止。

通常应用程序会等到所有非守护线程终止。