协程的创建

GlobalScope.launch

  • 使用(代码会在当前线程所有内容执行完成之后再执行)

    //新建线程,执行 "延时 1 秒,打印当前线程名称" 的代码
    GlobalScope.launch{
                delay(1000)
                Log.d(TAG, "createCoroutinesOne: ${Thread.currentThread().name}")
            }
    
    //在主线程中执行 "延时 1 秒,打印当前线程名称" 的代码
    GlobalScope.launch(Dispatchers.Main){
                delay(1000)
                Log.d(TAG, "createCoroutinesOne2: ${Thread.currentThread().name}")
            }
    
    //新建线程,执行 "延时 1 秒,打印当前线程名称" 的代码,在调用后,直接执行
    GlobalScope.launch(newSingleThreadContext("bin"), CoroutineStart.DEFAULT){
                delay(1000)
                Log.d(TAG, "createCoroutinesOne4: ${Thread.currentThread().name}")
            }
    
  • 参数

    public fun CoroutineScope.launch(
        context: CoroutineContext = EmptyCoroutineContext,
        start: CoroutineStart = CoroutineStart.DEFAULT,
        block: suspend CoroutineScope.() -> Unit
    ): Job {
    ...
    }
    
    • context: CoroutineContext
      协程调度器
    • start: CoroutineStart
      协程的启动模式
    • block: suspend CoroutineScope.()
      执行内容

runBlocking

  • 使用(代码会在调用位置直接执行。runBlocking 作用域内 launch 启动的代码,会在runBlocking 代码块其他代码执行完之后继续执行)

    runBlocking {
                delay(1000)
                Log.d(TAG, "createCoroutinesTwo3: ${Thread.currentThread().name}")
            }
    
    runBlocking{
                launch {
                    delay(1000)
                    Log.d(TAG, "createCoroutinesTwo: ${Thread.currentThread().name}")
                }
                Log.d(TAG, "createCoroutinesTwo2: ${Thread.currentThread().name}")
            }
    
  • 参数

    public fun <T> runBlocking(
    context: CoroutineContext = EmptyCoroutineContext,
     block: suspend CoroutineScope.() -> T): T {
    ...
    }
    
  • context: CoroutineContext = EmptyCoroutineContext
    协程调度器

  • block: suspend CoroutineScope.()
    执行内容

Dispatchers(协程调度器)

  • Dispatchers.Default
    在线程池中执行。适合CPU密集型的任务,比如解析JSON文件,排序一个较大的list
  • Dispatchers.Main
    表示主线程
  • Dispatchers.IO
    在线程池中执行。针对磁盘和网络IO进行了优化,适合IO密集型的任务,比如:读写文件,操作数据库以及网络请求
  • Dispatchers.Unconfined
    在调用的线程直接执行
  • newSingleThreadContext(name: String)
    使用新的线程

CoroutineStart(启动模式)

  • CoroutineStart.DEFAULT
    默认,不传或传入此参数会立即执行协程
  • CoroutineStart.LAZY
    launch后不立即执行,需要获取其job发起执行
  • CoroutineStart.UNDISPATCHED
    在协程代码块中优先级更高,更快执行
  • CoroutineStart.ATOMIC
    执行前不可取消的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值