1.thread { } 问题的发现
thread {
val token = "inapp:com.myart.kotlin:android.test.purchased"
val response = mService?.consumePurchase(3, packageName, token)
TLog.l("把已在库存中的商品,进行消耗 $response")
////惊天巨坑,重大BUG预警!!! thread { }语法糖,会自动开启线程启动!
}.start()
如上代码——>写完 thread { }后加上 .start() 方法,会执行两遍 TLog.l() 方法!!!
art.kotlin.com:Geek: 把已在库存中的商品,进行消耗 0
art.kotlin.com:Geek: 把已在库存中的商品,进行消耗 0
2.问题的缘由
点进去看thread { }的源码
public fun thread(start: Boolean = true,
isDaemon: Boolean = false,
contextClassLoader: ClassLoader? = null,
name: String? = null,
priority: Int = -1,
block: () -> Unit
): Thread {
val thread = object : Thread() {
public override fun run() {
block()
}
}
if (isDaemon)
thread.isDaemon = true
if (priority > 0)
thread.priority = priority
if (name != null)
thread.name = name
if (contextClassLoader != null)
thread.contextClassLoader = contextClassLoader
if (start)
thread.start()
return thread
}
可见,默认是自动自动的!并且会返回 thread的对象本身。
所以这里就非常容易出错。