【问题标题】:Kotlin process waits for all threads to finish?Kotlin 进程等待所有线程完成?
【发布时间】:2021-03-30 01:00:55
【问题描述】:

我写了这个简单的测试程序:

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

我的期望是至少不会打印“线程结束”消息, 导致主函数结束,这个主线程应该运行。

Kotlin 进程是否总是在等待线程完成后再完成?

【问题讨论】:

    标签: java multithreading kotlin parallel-processing


    【解决方案1】:

    您创建的线程是一个非守护线程,就像在Java中一样,JVM不会终止,直到所有非守护线程完成.

    来自Kotlin documentation 可以阅读:

    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 - 如果为真,则线程被创建为守护线程。 Java 当唯一运行的线程都是守护进程时,虚拟机退出 线程。

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

    name - 线程的名称。

    priority - 线程的优先级。

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

    Main Start
    Main End
    Thread Start
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      • 2022-01-23
      相关资源
      最近更新 更多