Kotlin的语法糖 thread { } 会运行两次的问题【重大BUG预警!】

没有检索到摘要

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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的对象本身。

所以这里就非常容易出错。

3.为了防止将来的隐患,赶紧在项目中 Ctrl + Alt +F 进行排查吧~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值