Kotlin进程等待所有线程完成?

4

I wrote this simple testing program:

fun main() {
    println("Main Start")

    thread {
        println("Thread Start")
        Thread.sleep(3000)
        println("Thread End")
    }

    println("Main End")
}

从我看到的,输出结果是:

Main Start
Main End
Thread Start
Thread End

我的期望是至少不会打印出 "Thread End" 信息,因为主函数已经结束,这个主线程应该也完成了运行。

Kotlin 进程是否总是等待线程完成后才算完成?

1个回答

5
您创建的线程是一个非守护线程,就像在Java中一样,只有当所有非守护线程完成时,JVM才会终止。
Kotlin文档中可以阅读到:
fun thread(
    start: Boolean = true, 
    isDaemon: Boolean = false, 
    contextClassLoader: ClassLoader? = null, 
    name: String? = null, 
    priority: Int = -1, 
    block: () -> Unit ): Thread Creates a thread that runs the specified block of code.

参数

start - 如果为true,则立即启动线程。

isDaemon - 如果为true,则创建的线程将作为守护线程。当所有运行的线程都是守护线程时,Java虚拟机将退出。

contextClassLoader - 用于在此线程中加载类和资源的类加载器。

name - 线程的名称。

priority - 线程的优先级。

Kotlin中的线程默认为非守护线程。这就是为什么即使主线程已经执行完毕,你仍然可以看到线程的输出。将isDaemon设置为true,则会看到以下输出:

Main Start
Main End
Thread Start

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接