Java 如何在 Kotlin 中初始化线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46505528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:23:29  来源:igfitidea点击:

How to initialize a Thread in Kotlin?

javamultithreadingkotlin

提问by Shubhranshu Jain

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

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

Thread myThread = new Thread(new myRunnable())

where myRunnableis a class implementing Runnable.

哪里myRunnable是一个实现Runnable.

But when I tried this in Kotlin, it doesn't seems to work:

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

var myThread:Thread = myRunnable:Runnable

回答by Rajesh Dalsaniya

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:

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

thread(start = true) {  
      println("running from thread(): ${Thread.currentThread()}")
    }

回答by s1m0nw1

For initialising an object of Threadyou simply invoke the constructor:

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

val t = Thread()

Then, you can also pass an optional Runnablewith a lambda (SAM Conversion) like this:

然后,您还可以Runnable像这样传递带有 lambda(SAM 转换)的可选项:

Thread {
    Thread.sleep(1000)
    println("test")
}

The more explicit version is passing an anonymous implementation of Runnablelike this:

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

Thread(Runnable {
    Thread.sleep(1000)
    println("test")
})

Note that the previously shown examples do only createan instance of a Threadbut don't actually start it. In order to achieve that, you need to invoke start()explicitly.

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

Last but not least, you need to know the standard library function thread, which I'd recommend to use:

最后但并非最不重要的一点是,您需要了解thread我建议使用的标准库函数:

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(start = true) {
    Thread.sleep(1000)
    println("test")
}

It has many optional parameters for e.g. directly starting the thread as shown here. Note that trueis the default value of startanyway.

它有许多可选参数,例如直接启动线程,如下所示。请注意,这truestart无论如何的默认值。

回答by Hardeep singh

Please try this code:

请试试这个代码:

Thread().run { Thread.sleep(3000); }

回答by Alexey Soshin

Best way would be to use thread()generator function from kotlin.concurrent: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.concurrent/thread.html

最好的方法是使用以下thread()生成器函数kotlin.concurrenthttps: //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.

请注意,您不需要start()像 Thread 示例中那样调用,也不需要提供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.

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

回答by Adam Hurwitz

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

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

Thread(Runnable {
            //some method here
        }).start()

回答by hgedek

fun main(args: Array<String>) {

    Thread({
        println("test1")
        Thread.sleep(1000)
    }).start()

    val thread = object: Thread(){
        override fun run(){
            println("test2")
            Thread.sleep(2000)
        }
    }

    thread.start()

    Thread.sleep(5000)
}

回答by Geet Thakur

Basic example of Threadwith Lamda

Threadwith的基本例子Lamda

fun main() {
    val mylamda = Thread({
        for (x in 0..10){
            Thread.sleep(200)
            println("$x")
        }
   })
    startThread(mylamda)

}

fun startThread(mylamda: Thread) {
    mylamda.start()
}

回答by David Callanan

thread { /* your code here */ }

回答by Coder

Firstly, create a function for set default propery

首先,创建一个设置默认属性的函数

fun thread(
  start: Boolean = true, 
  isDaemon: Boolean = false, 
  contextClassLoader: ClassLoader? = null, 
  name: String? = null, 
  priority: Int = -1, 
  block: () -> Unit
): Thread

then perform background operation calling this function

然后执行调用此函数的后台操作

thread(start = true) {
     //Do background tasks...
}

Or kotlin coroutines also can be used to perform background task

或者 kotlin 协程也可以用来执行后台任务

GlobalScope.launch {

    //TODO("do background task...")
    withContext(Dispatchers.Main) {
        // TODO("Update UI")
    }
    //TODO("do background task...")
}