的一個問題是,Thread
類的構造函數有一個參數糟糕的Kotlin訂單。對於Runnable
,您可以輕鬆使用SAM conversion(單個方法接口可以視爲lambda),但由於lambda不是最後一個參數,它看起來有點笨重。在那裏只有一個參數的情況下,它是罰款:
Thread { val a = 3 }.start()
然而,隨着多個參數,它們是向後造成這種醜陋的語法與拉姆達爲括號內的參數:
Thread({ val a = 3 }, "some name").start()
相反,你應該使用科特林STDLIB功能thread()
你所擁有的簡單的語法功能:
// create thread, auto start it, runs lambda in thread
thread { val a = 3 }
// create thread with given name, auto start it, runs lambda in thread
thread(name = "Cute Thread") { val a = 3 }
// creates thread that is paused, with a lambda to run later
thread(false) { val a = 3 }
// creates thread that is paused with a given name, with a lambda to run later
thread(false, name = "Cute Thread") { val a = 3 }
參見:thread()
function documentation
太棒了!謝謝! – PedroD
@PedroD答案已經現代化 –