multithreading - kotlin 嵌套线程 - "there is more than one label with such a name in this scope"

标签 multithreading kotlin

我有一些与此类似的 kotlin 代码:

Thread {
    ...
    Thread {
        ...
        return@Thread
        ...
    }.start()
    ...
}.start()

现在我收到以下警告:

enter image description here

我知道 kotlin 对此时我想返回哪个线程感到困惑,无论是外线程还是内线程。但我不确定如何告诉它,Android Studio 也没有多大帮助,因为它只建议编辑此警告的选项:

enter image description here

我尝试命名线程,并认为 kotlin 可能足够聪明来检查它,但我想这可能是不可能的,因为返回标签可能不会在运行时解释。

我意识到我可以将内线程导出到一个函数中,从而使线程不会相互干扰,如下所示:
Thread {
    ...
    startInnerThread()
    ...
}.start()

fun startInnerThread() {
    Thread {
        ...
        return@Thread
        ...
    }.start()
}

但我想知道是否可以更改标签 @Thread代替其中之一。

最佳答案

是的,您可以通过标记要返回的函数来做到这一点,如下所示:

Thread {

    Thread Foo@ {

        return@Foo

    }.start()

}.start()

关于multithreading - kotlin 嵌套线程 - "there is more than one label with such a name in this scope",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59774815/

相关文章:

kotlin - Tornadofx CSS选定的行

Android:notifyDataSetChanged()在方向改变后不更新 ListView

java - 如何停止 java 执行程序类中的所有可运行线程?

java - 通过多线程同时上传多个文件到 S3 抛出 java.nio.channels.ClosedChannelException : null

c++ - 如果在此调用之前未创建 abcd,那么 `std::map<..> a; blah = a[abcd];` 线程安全吗?

mongodb - 在 Kotlin 中,为什么 jackson 在某些情况下无法解码非注释对象而不是在其他情况下

java - 如何使用线程每次进行检查(例如在后台运行)直到我的条件为真

android - Android在TextView上每个字母周围的边框

android - 在 RecyclerView.Adapter 中绑定(bind) View 时出现 NullPointerException

android - RxJava2 与 Kotlin 协程