How to initialize a stream in Kotlin?

In Java, it works by accepting an object that implements runnable:

Thread myThread = new Thread(new myRunnable())

where myRunnableis the class that implements Runnable.

But when I tried this in Kotlin, it does not work:

var myThread:Thread = myRunnable:Runnable
+20
source share
7 answers

To initialize the object, Threadyou simply call the constructor:

val t = Thread()

Then you can also pass an optional Runnablewith a lambda expression (SAM conversion) as follows:

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

A more explicit version conveys an anonymous implementation Runnableas follows:

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

Note that the previously shown examples only create an instance Threadbut do not actually start it. For this you need to explicitly call start().

, : thread , :

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")
}

, , , . , true start.

+19

Runnable:

val myRunnable = runnable {

}

:

Thread({  
// call runnable here
  println("running from lambda: ${Thread.currentThread()}")
}).start()

Runnable: Kotlin . ? ! , :

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

, , .

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

, :

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

thread() kotlin.concurrent: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.concurrent/thread.html

, :

thread() { /* do something */ }

, start(), Thread, start=true.

, . thread(isDaemon= true), .

0
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)
}
0

Thread Lamda

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

}

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

Source: https://habr.com/ru/post/1686689/


All Articles