Kotlin GlobalScope 和 CoroutineScope

Kotlin 复制代码
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);

}
Kotlin 复制代码
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.一般都是用第一个,更加灵活。

相关推荐
pshdhx_albert3 小时前
AI agent实现打字机效果
java·http·ai编程
沉鱼.443 小时前
第十二届题目
java·前端·算法
qq_381013744 小时前
IntelliJ IDEA中GitHub Copilot完整使用教程:从安装到实战技巧
其他·github·intellij-idea·copilot
赫瑞4 小时前
数据结构中的排列组合 —— Java实现
java·开发语言·数据结构
周末也要写八哥5 小时前
多进程和多线程的特点和区别
java·开发语言·jvm
惜茶6 小时前
vue+SpringBoot(前后端交互)
java·vue.js·spring boot
杰克尼7 小时前
springCloud_day07(MQ高级)
java·spring·spring cloud
NHuan^_^8 小时前
SpringBoot3 整合 SpringAI 实现ai助手(记忆)
java·人工智能·spring boot
Mr_Xuhhh8 小时前
从ArrayList到LinkedList:理解链表,掌握Java集合的另一种选择
java·数据结构·链表
错把套路当深情9 小时前
Java 全方向开发技术栈指南
java·开发语言