Kotlin 中的线程 lambda 表达式

thread lambda expression in Kotlin

示例代码:

fun main() {
   thread(name = "Worker Thread") {
        for (i in 1..5) {
            println(Thread.currentThread().name)
        }
    }
    println(Thread.currentThread().name)
}

上述示例的反编译字节码:

public final class PracKt {
   public static final void main() {
      ThreadsKt.thread$default(false, false, (ClassLoader)null, "Worker Thread", 0, (Function0)null.INSTANCE, 23, (Object)null);
      Thread var10000 = Thread.currentThread();
      Intrinsics.checkNotNullExpressionValue(var10000, "Thread.currentThread()");
      String var0 = var10000.getName();
      boolean var1 = false;
      System.out.println(var0);
   }

   // $FF: synthetic method
   public static void main(String[] var0) {
      main();
   }
}

代码工作正常,但我无法在反编译代码中理解如何在不调用 start() 方法的情况下执行线程。如果我尝试在示例代码中调用 thread.start(),则会抛出 IllegalThreadStateException

如果未在反编译代码中显示,start() 方法在哪里被调用?

Kotlin docs 开始。当您使用方法 thread 时,创建的线程默认启动。

fun thread(
    start: Boolean = true,
    isDaemon: Boolean = false,
    contextClassLoader: ClassLoader? = null,
    name: String? = null,
    priority: Int = -1,
    block: () -> Unit
): Thread

要显式启动它,您应该将 start 标志设置为 false