kotlin创建简单多线程的3种方式
import kotlin.concurrent.thread
fun main(args: Array<String>) {
//方式1
object : Thread() {
override fun run() {
sleep(1500)
val ct = currentThread()
println("$ct")
}
}.start()
// 方式2
val t = Thread {
Thread.sleep(1000)
val ct = Thread.currentThread()
println("$ct")
}
t.isDaemon = false
t.name = "my-thread-"
t.priority = 2
t.start()
// 方式3
thread(start = true, isDaemon = false, name = "my-thread--", priority = 3) {
Thread.sleep(500)
val ct = Thread.currentThread()
println("thread() : $ct")
}
}
输出:
thread() : Thread[my-thread--,3,main]
Thread[my-thread-,2,main]
Thread[Thread-0,5,main]