[英]thread lambda expression in Kotlin
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.代码工作正常,但我无法在反编译代码中理解如何在不调用start()
方法的情况下执行线程。 If I try to call thread.start()
in sample code, IllegalThreadStateException is thrown.如果我尝试在示例代码中调用thread.start()
。
Where is start()
method is getting called if not shown in decompiled code?如果未在反编译代码中显示start()
方法在哪里被调用?
As it goes from Kotlin docs .从Kotlin docs 开始。 When you're using method thread
, created thread is started by default.当您使用方法thread
时,默认情况下会启动创建的线程。
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
.要显式启动它,您应该将start
标志设置为false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.