How to initialize a Thread in Kotlin?

2020-06-30 08:57发布

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

Thread myThread = new Thread(new myRunnable())

where myRunnable is a class implementing Runnable.

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

var myThread:Thread = myRunnable:Runnable

9条回答
啃猪蹄的小仙女
2楼-- · 2020-06-30 09:48

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:

thread(start = true) {  
      println("running from thread(): ${Thread.currentThread()}")
    }
查看更多
老娘就宠你
3楼-- · 2020-06-30 09:48

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

Thread(Runnable {
            //some method here
        }).start()
查看更多
够拽才男人
4楼-- · 2020-06-30 09:49
thread { /* your code here */ }
查看更多
登录 后发表回答