如何在Kotlin中初始化一个线程? [英] How to initialize a Thread in Kotlin?
问题描述
在Java中它通过接受一个实现runnable的对象来工作:
In Java it works by accepting an object which implements runnable :
Thread myThread = new Thread(new myRunnable())
其中 myRunnable
是一个实现<$的类C $ C>可运行。
但是当我在Kotlin尝试这个时,它似乎不起作用:
But when I tried this in Kotlin, it doesn't seems to work:
var myThread:Thread = myRunnable:Runnable
推荐答案
初始化 Thread
的对象时,只需调用构造函数:
For initialising an object of Thread
you simply invoke the constructor:
val t = Thread()
然后,您还可以传递一个可选的带有lambda(SAM转换)的Runnable
,如下所示:
Then, you can also pass an optional Runnable
with a lambda (SAM Conversion) like this:
Thread {
Thread.sleep(1000)
println("test")
}
越多显式版本传递 Runnable
的匿名实现,如下所示:
The more explicit version is passing an anonymous implementation of Runnable
like this:
Thread(Runnable {
Thread.sleep(1000)
println("test")
})
请注意,之前显示的示例仅创建 Thread
的实例,但实际上并未启动它。为了实现这一点,你需要明确地调用 start()
。
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.
最后但并非最不重要的,你需要要知道标准库函数 thread
,我建议使用它:
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 {
您可以像这样使用它:
thread(start = true) {
Thread.sleep(1000)
println("test")
}
它有许多可选参数,例如直接启动线程,如下所示。
It has many optional parameters for e.g. directly starting the thread as shown here.
这篇关于如何在Kotlin中初始化一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!