Kotlin GlobalScope 和 CoroutineScope

package com.tiger.mykotlinapp.scope

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

fun main() {

    val  globalScope = GlobalScope
    globalScope.launch {
        delay(3000)
        println("hello")
    }

    globalScope.launch {
        delay(3000)
        println("hello")
    }

    //因为globalScope是整个应用程序的生命周期,不能在此手动取消它,调用抛异常 java.lang.IllegalStateException: Scope cannot be cancelled because it does not have a job
    globalScope.cancel()//不能手动取消它
    while (true);

}
package com.tiger.mykotlinapp.scope

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

fun main() {

    val coroutineScope = CoroutineScope(Dispatchers.Default)
    coroutineScope.launch {
        delay(3000)
        println("hello")
    }
    coroutineScope.launch {
        delay(3000)
        println("hello")
    }
    //发现可以取消
    coroutineScope.cancel()
    while (true);

}

CoroutineScope和GlobalScope的区别

1. 作用域不同,第一个作用域是activity,第二个是全局整个应用程序

2.第一个可以取消,第二个取消会抛异常

3.一般都是用第一个,更加灵活。

相关推荐

  1. Kotlin GlobalScope CoroutineScope

    2024-01-18 01:50:02       54 阅读
  2. @RequestBody@RequestParam@PathVariable@RequestAttribute

    2024-01-18 01:50:02       53 阅读
  3. ==equals

    2024-01-18 01:50:02       60 阅读
  4. 关于%/

    2024-01-18 01:50:02       42 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-18 01:50:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-18 01:50:02       101 阅读
  3. 在Django里面运行非项目文件

    2024-01-18 01:50:02       82 阅读
  4. Python语言-面向对象

    2024-01-18 01:50:02       91 阅读

热门阅读

  1. vue3自定义指令

    2024-01-18 01:50:02       64 阅读
  2. 带头双向循环链表基础

    2024-01-18 01:50:02       51 阅读
  3. ubuntu server配置无线网络

    2024-01-18 01:50:02       53 阅读
  4. .gitignore文件设置了忽略但不生效

    2024-01-18 01:50:02       55 阅读
  5. Python中英文时间转换

    2024-01-18 01:50:02       62 阅读
  6. Ubuntu中用useradd创建用户后无法用su切换过去

    2024-01-18 01:50:02       54 阅读