You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin调用kotlin.concurrency.thread报错:Unresolved reference: thread

解决Kotlin中thread函数找不到的问题

你遇到的Unresolved reference: thread错误,主要是因为缺少正确的导入或依赖配置,下面一步步帮你解决:

  • 第一步:添加正确的导入语句
    thread函数属于kotlin.concurrent包,你需要在代码文件顶部添加这个导入:

    import kotlin.concurrent.thread
    

    没有这个导入的话,编译器找不到这个扩展函数。

  • 第二步:确认Kotlin标准库依赖
    在Android项目的build.gradle(Module level)文件中,确保已经引入了Kotlin标准库依赖(通常Android Studio创建项目时会自动添加,但如果手动修改过配置可能会丢失):

    dependencies {
        implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
        // 如果你用的是Kotlin 1.8+,也可以用kotlin-stdlib-jdk8,包含更多JDK8相关API
        // implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    }
    

    记得把$kotlin_version替换成你项目中使用的Kotlin版本号,比如1.9.20。

  • 额外的代码优化建议
    你的代码还有两个小问题可以优化:

    1. Kotlin中建议使用Int而非Java的Integer,所以参数类型可以改成userId: Int
    2. 你创建的CustomExceptionHandler(context)只是实例化了对象,但没有绑定到线程上,应该在线程块内部设置未捕获异常处理器:
      fun identify(userId: Int) {
          thread {
              Thread.currentThread().uncaughtExceptionHandler = CustomExceptionHandler(context)
              DoStuffClass.doStuff(context, userId)
          }
      }
      
      或者也可以直接在thread函数的参数中指定(前提是CustomExceptionHandler实现了Thread.UncaughtExceptionHandler接口):
      fun identify(userId: Int) {
          thread(uncaughtExceptionHandler = CustomExceptionHandler(context)) {
              DoStuffClass.doStuff(context, userId)
          }
      }
      

内容的提问来源于stack exchange,提问作者Abraham P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:38:03