美文网首页
安卓协程那些事2-协程上下文Coroutine Context

安卓协程那些事2-协程上下文Coroutine Context

作者: itBox | 来源:发表于2022-06-29 14:16 被阅读0次

本文介绍什么是协程上下文,及如何利用协程上下文

先看一段代码

package com.android.coroutineTest
import ...
class MainActivity : AppCompatActivity() {
    GlobalScope.launch(Dispatchers.IO){
            Log.d(TAG, "Starting coroutine in thread ${Thread.currentThread().name}")
            val answer = doNetReq()
            withContext(Dispatchers.Main){
                Log.d(TAG, "Setting text in thread ${Thread.currentThread().name}")
                binding.btnTestDownFromTFCard.text = answer
            }
        }
//suspend 必须加
private suspend fun doNetReq(): String {
        delay(3000L)
        return "result is cool."
    }

以上代码功能为在主线程修改Button的文字,使用 withContext 配合 Dispatchers.Main 实现。

delay 是 suspend 方法

suspend 方法只能在 协程中使用,且内调用 suspend 方法的方法也必须是 suspend。(有点绕)

Dispatchers 是什么?

源码注释:The CoroutineDispatcher that is designed for offloading blocking IO tasks to a shared pool of threads.

Dispatchers 属性介绍
Dispatchers.IO 操作数据
Dispatchers.Main 主线程(UI线程)
Dispatchers.Default 用于CPU计算任务

区别:

The difference is that Dispatchers.Default is limited to the number of CPU cores (with a minimum of 2) so only N (where N == cpu cores) tasks can run in parallel in this dispatcher.
On the IO dispatcher there are by default 64 threads, so there could be up to 64 parallel tasks running on that dispatcher.
The idea is that the IO dispatcher spends a lot of time waiting (IO blocked), while the Default dispatcher is intended for CPU intensive tasks, where there is little or no sleep.

协程使用步骤

添加依赖

implementation  'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0'

获取当前线程名

Thread.currentThread().name

关于 delay

delay是一个顶级函数,由于它被suspend修饰,所以只能用在协程或者被其他suspend函数修饰,它的功能为

delay( 1000L )

将当前协程延迟一个给定时间,但是不会阻塞当前线程 并且它也是可以被取消的

suspend 方法

suspend使用案例
https://www.jianshu.com/p/0eea02e7bc29

如果这篇文章有帮助到你,请帮忙点点赞,感谢

相关文章

  • 安卓协程那些事2-协程上下文Coroutine Context

    本文介绍什么是协程上下文,及如何利用协程上下文 先看一段代码 以上代码功能为在主线程修改Button的文字,使用 ...

  • JVM配置项-Dkotlinx.coroutines.debug

    背景介绍 最近在学习Kotlin的Coroutine(协程)部分,在 Coroutine Context and ...

  • 协程

    协程,又称微线程,纤程。英文名Coroutine。协程是一种用户态的轻量级线程。协程拥有自己的寄存器上下文和栈。协...

  • python异步协程(aiohttp,asyncio)

    python异步协程 环境:python3.7.0 协程 协程,英文叫做 Coroutine,又称微线程,纤程,协...

  • Kotlin协程探索(一) (Coroutine)

    Kotlin协程探索 (一)(Coroutine) PS:以下协程都特指Kotlin协程;且期望大家大概知道协程的...

  • Python 协程

    仅供学习,转载请注明出处 协程 协程,又称微线程,纤程。英文名Coroutine。 协程是啥 协程是python个...

  • 协程

    1.协程 协程,又称微线程,纤程。英文名Coroutine。 1.1 协程是什么 协程是python个中另外一种实...

  • Python并发编程——协程

    摘要:Python,协程,gevent 协程基本概念 协程,又称微线程,纤程。英文名Coroutine,是Pyth...

  • 协程介绍

    协程 协程,又称微线程,纤程。英文名Coroutine。 1.协程是什么? 协程是python个中另外一种实现多任...

  • 4-7

    协程 协程,又称微线程,纤程。英文名Coroutine。 协程是啥 协程是python个中另外一种实现多任务的方式...

网友评论

      本文标题:安卓协程那些事2-协程上下文Coroutine Context

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