Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

kotlin - Kotlin coruntines在启动和回调中不会执行(Kotlin coruntines wont execute when in a launch and callback)

I thought I was familiar enough with Kotlin's coroutines, until I got this code.

(我以为我对Kotlin的协程足够熟悉,直到获得此代码。)

1 to 8 are all printed except 2:

(除2以外,全部打印1至8:)

import kotlinx.coroutines.*
import java.lang.Runnable
import java.lang.Thread.sleep
import kotlin.concurrent.thread

fun main() {
    runBlocking {
        Client.createAccount()
        delay(1000)
    }
}

object Client: CoroutineScope {
    override val coroutineContext = newSingleThreadContext("Client")

    fun createAccount() = launch {
        Client2.init(Runnable {
            println('1')
            launch {
                println('2')
            }
            ok()
            ok2()
        })

        println('7')
        launch {
            println('8')
        }
    }

    fun ok() {
        println('3')
        launch {
            println('4')
        }
    }

    fun ok2() = launch {
        println('5')
        launch {
            println('6')
        }
    }
}

object Client2 {

    fun init(runnable: Runnable) = thread {
        sleep(100)
        runnable.run()
    }
}

The result is:

(结果是:)

7
8
1
3
4
5
6

The coroutine in callback will never be called.

(回调中的协程将永远不会被调用。)

Why?

(为什么?)

And if I remove the launch in createAccount() the 1 to 8 will be all printed.

(如果我在createAccount()删除launch ,则将全部打印1至8。)

Also if I use GlobalScope.launch { println('2') } instead of launch { println('2') } , I can also get the 2 printed.

(同样,如果我使用GlobalScope.launch { println('2') }而不是launch { println('2') } ,我也可以打印出2。)

  ask by sickworm translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...