Koltin 多线程 - 创建像线程的方式(继承 Thread 类、实现 Runnable 接口、使用匿名内部类、使用 Lambda 表达式、Kotlin 的 thread 函数)
·
一、继承 Thread 类
class MyThread : Thread() {
override fun run() {
println("线程运行中: ${currentThread().name}")
}
}
val thread = MyThread()
thread.start()
二、实现 Runnable 接口
class MyRunnable : Runnable {
override fun run() {
println("线程运行中: ${Thread.currentThread().name}")
}
}
val thread = Thread(MyRunnable())
thread.start()
三、使用匿名内部类
- 匿名 Thread
Thread(object : Thread() {
override fun run() {
println("线程运行中: ${currentThread().name}")
}
}).start()
- 匿名 Runnable
Thread(Runnable {
println("线程运行中: ${Thread.currentThread().name}")
}).start()
四、使用 Lambda 表达式
Thread({
println("线程运行中: ${Thread.currentThread().name}")
}).start()
// 最简洁的形式,Lambda 表达式是最后一个参数时可以省略括号
Thread {
println("线程运行中: ${Thread.currentThread().name}")
}.start()
五、Kotlin 的 thread 函数
1、基本介绍
public fun thread(
start: Boolean = true,
isDaemon: Boolean = false,
contextClassLoader: ClassLoader? = null,
name: String? = null,
priority: Int = -1,
block: () -> Unit
): Thread {
...
}
| 参数 | 说明 |
|---|---|
| start | 设置是否自动启动线程 |
| isDaemon | 设置是否为守护线程 |
| contextClassLoader | 设置线程的上下文类加载器 |
| name | 设置线程名称 |
| priority | 设置线程优先级 |
| block | 设置线程要执行的代码块 |
2、演示
thread {
println("Kotlin Thread: ${Thread.currentThread().name}")
}
thread(
name = "MyKotlinThread",
priority = 5
) {
println("Kotlin Thread: ${Thread.currentThread().name}")
}
更多推荐

所有评论(0)