• Coroutines协程示例


    1. .gradle中引入库

    1. //协程
    2. implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1"
    3. implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1"

    2. 创建 CoroutinesTest.kt

    1. class CoroutinesTest {
    2. @Test
    3. fun testCoroutines() {
    4. }
    5. }

    3. launch 异步示例
      3.1 launch,异步,不阻塞线程

    1. /**
    2. * 1.launch,异步,不阻塞线程
    3. * GlobalScope.launch 具有生命中周期
    4. */
    5. private fun testLaunch() {
    6. val time: Long = measureTimeMillis {
    7. GlobalScope.launch {
    8. Thread.sleep(1000)
    9. println("testLaunch 的launch 中, ${Thread.currentThread()} Good")
    10. }
    11. GlobalScope.launch {
    12. Thread.sleep(1000)
    13. println("testLaunch 的launch2 中, ${Thread.currentThread()} Good")
    14. }
    15. println("Hello? ${Thread.currentThread()}")
    16. //由于代码函数生命周期的缘故,这里执行完代码块,jvm就销毁了函数栈,所有需要等待一下,才能看到 launch 的异步代码块的效果
    17. Thread.sleep(2200)
    18. }
    19. println("函数总耗时 $time")
    20. }

      3.2 调用及输出结果

    1. testLaunch()
    2. /*Hello? Thread[Test worker,5,main]
    3. testLaunch 的launch2 中, Thread[DefaultDispatcher-worker-3 @coroutine#2,5,main] Good
    4. testLaunch 的launch 中, Thread[DefaultDispatcher-worker-2 @coroutine#1,5,main] Good
    5. 函数总耗时 2254*/

    4. async 异步示例
      4.1 async异步,不阻塞线程

    1. /**
    2. * 2.async,异步,不阻塞线程
    3. * CoroutinesScope.async,具有生命周期的
    4. */
    5. private fun testAsync() {
    6. val time: Long = measureTimeMillis {
    7. GlobalScope.async {
    8. Thread.sleep(1000)
    9. println("testAsync 的 async 中, ${Thread.currentThread()} Good")
    10. }
    11. GlobalScope.async {
    12. Thread.sleep(1000)
    13. println("testAsync 的 async2 中, ${Thread.currentThread()} Good")
    14. }
    15. println("Hello ${Thread.currentThread()}")
    16. //由于代码函数生命周期的缘故,这里执行完代码块,jvm就销毁了函数栈,所有需要等待一下,才能看到 async 的异步代码块的效果
    17. Thread.sleep(2200)
    18. }
    19. println("函数总耗时: $time")
    20. }

      4.2 调用及输出结果

    1. testAsync()
    2. /*Hello Thread[Test worker,5,main]
    3. testAsync 的 async 中, Thread[DefaultDispatcher-worker-1 @coroutine#1,5,main] Good
    4. testAsync 的 async2 中, Thread[DefaultDispatcher-worker-3 @coroutine#2,5,main] Good
    5. 函数总耗时: 2251*/

    5. runBlocking 示例
      5.1 runBlocking,阻塞线程

    1. /**
    2. * 3. runBlocking,阻塞线程
    3. * 桥接普通函数和协程
    4. */
    5. private fun testRunBlocking() {
    6. var time: Long = measureTimeMillis {
    7. runBlocking {
    8. println("testRunBlocking 的block中 ${Thread.currentThread()} before delay")
    9. delay(500)
    10. println("testRunBlocking 的block中 ${Thread.currentThread()} -- after delay --")
    11. }
    12. println("testRunBlocking ${Thread.currentThread()} Hello")
    13. }
    14. println("函数总耗时: $time")
    15. }

      5.2 调用及输出结果

    1. testRunBlocking()
    2. /* testRunBlocking 的block中 Thread[Test worker @coroutine#1,5,main] before delay
    3. testRunBlocking 的block中 Thread[Test worker @coroutine#1,5,main] -- after delay --
    4. testRunBlocking Thread[Test worker,5,main] Hello
    5. 函数总耗时: 559*/

    6. cancel join 示例
      6.1 cancel join runBlocking 会等待内部协程执行完毕才结束

    1. /**
    2. * 4. cancel join
    3. * runBlocking 会等待内部协程执行完毕才结束,对比 test1 的jvm
    4. * 异步的特性,注意执行输出的结果
    5. */
    6. private fun testCancelJoin() = runBlocking {
    7. var time: Long = measureTimeMillis {
    8. val L1: Job = launch {
    9. //Thread.sleep(1000)
    10. println("testCancelJoinTimeOut >> Launch1 ${Thread.currentThread()} L1 Hello")
    11. }
    12. val L2: Job = launch {
    13. println("testCancelJoinTimeOut >> Launch2 ${Thread.currentThread()} L2 Hello")
    14. }
    15. var a2 = async {
    16. repeat(20) {
    17. println("testCancelJoinTimeOut >> async2 ${Thread.currentThread()} $it A2 Good")
    18. delay(200)
    19. //Thread.sleep(1000)
    20. }
    21. }
    22. //a2.cancelAndJoin()//取消协程,并返回主协程
    23. // a2.join()//如此则必须 a2 结束协程,才会走下面的
    24. var a1 = async {
    25. println("testCancelJoinTimeOut >> async ${Thread.currentThread()} A1 Hello")
    26. //测试取消 a2
    27. a2.cancel()
    28. }
    29. println("testCancelJoinTimeOut ${Thread.currentThread()} Out")
    30. }
    31. println("函数总耗时 $time")
    32. }

      6.2 调用及输出结果

    1. testCancelJoin()
    2. /* testCancelJoinTimeOut Thread[Test worker @coroutine#1,5,main] Out
    3. 函数总耗时 8
    4. testCancelJoinTimeOut >> Launch1 Thread[Test worker @coroutine#2,5,main] L1 Hello
    5. testCancelJoinTimeOut >> Launch2 Thread[Test worker @coroutine#3,5,main] L2 Hello
    6. testCancelJoinTimeOut >> async2 Thread[Test worker @coroutine#4,5,main] 0 A2 Good
    7. testCancelJoinTimeOut >> async Thread[Test worker @coroutine#5,5,main] A1 Hello*/
    8. 7.time out 示例

    7. time out 示例
      7.1 执行超时抛出异常

    1. /**
    2. * 5. time out
    3. * 执行超时抛出异常
    4. */
    5. private fun testTimeOut() = runBlocking {
    6. val time = measureTimeMillis {
    7. //超时自动取消内部协程,抛异常
    8. withTimeout(2000) {
    9. // repeat(200) {
    10. // println("withTimeOut 的${Thread.currentThread()} $it")
    11. // delay(300)
    12. // }
    13. launch {
    14. repeat(200) {
    15. println("withTimeOut中 launch 的 ${Thread.currentThread()} $it")
    16. delay(300)
    17. }
    18. }
    19. println("withTimeOut ${Thread.currentThread()}")
    20. }
    21. withTimeoutOrNull(1000) {
    22. println("withTimeoutOrNull ${Thread.currentThread()}")
    23. }
    24. }
    25. println("函数总耗时 ----- $time")
    26. }

      7.2 调用及输出结果

    1. //testTimeOut()
    2. /* withTimeOut Thread[Test worker @coroutine#1,5,main]
    3. withTimeOut中 launch 的 Thread[Test worker @coroutine#2,5,main] 0
    4. withTimeOut中 launch 的 Thread[Test worker @coroutine#2,5,main] 1
    5. withTimeOut中 launch 的 Thread[Test worker @coroutine#2,5,main] 2
    6. withTimeOut中 launch 的 Thread[Test worker @coroutine#2,5,main] 3
    7. withTimeOut中 launch 的 Thread[Test worker @coroutine#2,5,main] 4
    8. withTimeOut中 launch 的 Thread[Test worker @coroutine#2,5,main] 5
    9. withTimeOut中 launch 的 Thread[Test worker @coroutine#2,5,main] 6
    10. Timed out waiting for 2000 ms
    11. kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 2000 ms*/

    8. await 示例
      8.1 await,async的异步deferred结果获取

    1. /**
    2. * await,async的异步deferred结果获取
    3. */
    4. private fun testAwait() = runBlocking {
    5. val time: Long = measureTimeMillis {
    6. val a2 = async {
    7. println("testAwait ${Thread.currentThread()} A2 Good")
    8. delay(3000)
    9. 100
    10. }
    11. //a2.join()
    12. val a1 = async {
    13. getA1()
    14. }
    15. //a1.join()
    16. println("result ${Thread.currentThread()} -- ${a1.await()} ${a2.await()}")
    17. }
    18. println("函数总耗时: $time")
    19. }
    20. //suspend fun 挂起函数
    21. private suspend fun getA1(): Int {
    22. println("testAwait>>async ${Thread.currentThread()} A1 Good")
    23. delay(2000)
    24. return 99
    25. }

      8.2 调用及输出结果

    1. testAwait()
    2. /* testAwait Thread[Test worker @coroutine#2,5,main] A2 Good
    3. testAwait>>async Thread[Test worker @coroutine#3,5,main] A1 Good
    4. result Thread[Test worker @coroutine#1,5,main] -- 99 100
    5. 函数总耗时: 3013*/

  • 相关阅读:
    Yum 和 Rpm 安装包管理软件的区别 - 分布式网络包仓库管理 - 手动包管理
    【Vue轮播插件】常用的vue轮播插件整理
    python字面量
    25分钟了解命令执行漏洞【例题+详细讲解】(一)
    全网最新版的超详细的xxl_job教程(2023年),以及解决“调度失败:执行器地址为空”的问题
    128.(前端)增加商品前数据处理——将二维数组转成字符串形式传递
    闭关之 Vulkan 应用开发指南笔记(二):队列、命令、移动数据和展示
    node.js学习之路由、中间件
    Android View自定义参数declare-styleable介绍与使用
    京东商品分类API接口-(cat_get-获得jd商品分类API接口),京东分类API接口
  • 原文地址:https://blog.csdn.net/u011193452/article/details/126262338