Home > Back-end >  thread lambda expression in Kotlin
thread lambda expression in Kotlin

Time:12-04

Sample code:

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

Decompiled bytecode for the above sample:

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();
   }
}

Code works fine but I can't understand in decompiled code how thread gets executed without calling start() method. If I try to call thread.start() in sample code, IllegalThreadStateException is thrown.

Where is start() method is getting called if not shown in decompiled code?

CodePudding user response:

As it goes from Kotlin docs. When you're using method thread, created thread is started by default.

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

To start it explicitly, you should set start flag to false.

  • Related