美文网首页
Kotlin-协程

Kotlin-协程

作者: 335a40e49285 | 来源:发表于2020-10-09 00:13 被阅读0次

开启线程的方式

  1. 使用 runBlocking 顶层函数。一般用于测试。
runBlocking { 
}
  1. 使用 GlobalScope 单例对象。也是顶层协程。
GlobalScope.launch {
}
  1. 创建 CoroutineScope 对象。
CoroutineScope(Dispatchers.XX).launch {
}
  1. launch,会在协程域中再开子协程。
runBlocking {
    launch {  }
}
  1. async方式,会在协程域中再开子协程。返回值是一个实现了Job接口的Dererred对象。
runBlocking {
    async {
    }
}

asnyc会返回一个Dererred对象。如果想要获得async函数代码块的运行结果,可以调用Dererred的await()方法。

runBlocking {
    val deferred = async {
    1+1
    }
    println(deferred.await())
}

await()方法会阻塞当前协程,直到获取到async函数的结果。

Dispatchers指定线程

  1. Dispatchers.Main:Android 中的主线程
  2. Dispatchers.IO:针对磁盘和网络 IO 进行了优化,适合 IO 密集型的任务,比如:读写文件,操作数据库以及网络请求
  3. Dispatchers.Default:适合 CPU 密集型的任务,比如计算
  4. Dispatchers.Unconfined:不推荐使用
runBlocking {
    withContext(Dispatchers.Main){
    }
    withContext(Dispatchers.IO){
    }
    withContext(Dispatchers.Default){
    }
}

suspend 关键字修饰的函数

表示该函数需要在协程中调用。

private suspend fun test(string:String) {
    println(string)
}

private suspend fun test(string:String) = withContext(Dispatchers.IO){
}

private suspend fun test(string:String) :String = withContext(Dispatchers.IO){
    "xxx"
}

协程代码块中代码运行到suspend函数时,会暂时不再执行剩余的协程代码,而是先执行完suspend函数在继续往下执行。

fun main(arg: Array<String>) {
    CoroutineScope(Dispatchers.Default).launch {
        println("1")
        test() // 运行到suspend函数,会执行完suspend函数之后再往下执行
        println("2")
    }
    Thread.sleep(6000)
    println("end")
}

suspend fun test() {
    delay(3000)
    println("test")
}

运行结果
1
test
2
end

子协程launch代码块

子协程launch代码块不会影响后面代码的运行(因为子协程本来就是新的协程,和原来的代码块分开各跑各的)。

fun main(arg: Array<String>) {
    CoroutineScope(Dispatchers.Default).launch {
        launch { // 新的子协程,不影响后面代码的运行
            delay(3000)
            println("0")
        }
        test()
        println("1")
    }
    Thread.sleep(6000)
    println("end")
}

suspend fun test() {
    delay(1000)
    println("test")
}

运行结果
test
1
0
end

相关文章

  • Kotlin-协程

    开启线程的方式 使用 runBlocking 顶层函数。一般用于测试。 使用 GlobalScope 单例对象。也...

  • kotlin-协程

    Why 简化异步代码的编写。 执行严格主线程安全确保你的代码永远不会意外阻塞主线程,并增强了代码的可读性。 提升代...

  • Kotlin-协程

    协程的定义 协程可以理解为一种轻量级的线程。协程和线程的区别是线程是依靠操作系统的调度才能实现不同线程之间的切换的...

  • Kotlin-协程

    1.什么是协程? 是一套基于线程的API框架,重点:还是基于线程。 2.协程有什么用? 可以灵活地切换线程,用同步...

  • Kotlin - Lambda 表达式

    下一篇:Kotlin-协程[https://www.jianshu.com/p/ccb372840eec] Kot...

  • Kotlin-协程的取消关键技术分析

    Kotlin-协程的取消关键技术分析 RUN> ??????hello: 0hello: 1hello: 2hel...

  • Kotlin-协程基础

    第一个协程 根据官方文档 可以了解到 以下例子: 上面的例子 运行后 : 为何直接打印“主线程执行结束”而没有执行...

  • (转)Kotlin-协程

    上一篇:Kotlin - Lambda 表达式[https://www.jianshu.com/p/6899025...

  • Kotlin-协程-构建器

    构建器 runBlocking 顶层函数非挂起函数返回T,Lambda表达值最后一行 阻塞当前线程,会等待所有其中...

  • Kotlin-协程网络请求封装

    依赖 封装步骤 1.配置Retrofit、okhttp 2.请求数据转换 2.1 创建请求接口apiService...

网友评论

      本文标题:Kotlin-协程

      本文链接:https://www.haomeiwen.com/subject/bbdkpktx.html