【问题标题】:Unresolved reference thread未解决的参考线程
【发布时间】:2018-11-10 07:02:29
【问题描述】:

我正在尝试使用 kotlin.concurrency.thread 在 kotlin for android 中启动一个新线程但是我不断收到:

 Unresolved reference: thread

我以为这是在标准库中?

实际代码:

fun identify(userId: Integer) {
    thread() {
      CustomExceptionHandler(context)
      DoStuffClass.doStuff(context, userId)
    }
  }

【问题讨论】:

  • 你为你的jdk版本添加了stdlib吗?看这里:kotlinlang.org/docs/reference/…
  • 是的,我在我的依赖项中包含了 kotlin-stdlib-jdk8: implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"

标签: multithreading concurrency kotlin standard-library


【解决方案1】:

正确的导入语句是:

import kotlin.concurrent

示例代码应该是:

fun identify(userId: Integer) {
    thread {
        CustomExceptionHandler(context)
        DoStuffClass.doStuff(context, userId)
    }
}

因为thread函数定义为:

/**
 * Creates a thread that runs the specified [block] of code.
 *
 * @param start if `true`, the thread is immediately started.
 * @param isDaemon if `true`, the thread is created as a daemon thread. The Java Virtual Machine exits when
 * the only threads running are all daemon threads.
 * @param contextClassLoader the class loader to use for loading classes and resources in this thread.
 * @param name the name of the thread.
 * @param priority the priority of the thread.
 */
public fun thread(
    start: Boolean = true,
    isDaemon: Boolean = false,
    contextClassLoader: ClassLoader? = null,
    name: String? = null,
    priority: Int = -1,
    block: () -> Unit
): Thread {
    ...
}

正如here 所解释的,thread 函数使用 lambda 作为最后一个参数,然后,根据 Kotlin 语法,单个参数函数不需要括号,只需 lambda 块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2021-08-17
    • 2016-12-14
    • 2020-05-27
    • 2019-11-16
    相关资源
    最近更新 更多