栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

协程的创建

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

协程的创建

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  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
    执行前不可取消的
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1020629.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号