Coroutines协程示例

1. .gradle中引入库

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

2. 创建 CoroutinesTest.kt

class CoroutinesTest {
    @Test
    fun testCoroutines() {
    }
}

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

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

  3.2 调用及输出结果

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

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

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

  4.2 调用及输出结果

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

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

    /**
     * 3. runBlocking,阻塞线程
     * 桥接普通函数和协程
     */
    private fun testRunBlocking() {
        var time: Long = measureTimeMillis {
            runBlocking {
                println("testRunBlocking 的block中 ${Thread.currentThread()} before delay")
                delay(500)
                println("testRunBlocking 的block中 ${Thread.currentThread()} -- after delay --")
            }
            println("testRunBlocking ${Thread.currentThread()} Hello")
        }
        println("函数总耗时: $time")
    }

  5.2 调用及输出结果

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

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

    /**
     * 4. cancel join
     * runBlocking 会等待内部协程执行完毕才结束,对比 test1 的jvm
     * 异步的特性,注意执行输出的结果
     */
    private fun testCancelJoin() = runBlocking {
        var time: Long = measureTimeMillis {
            val L1: Job = launch {
                //Thread.sleep(1000)
                println("testCancelJoinTimeOut >> Launch1 ${Thread.currentThread()} L1 Hello")
            }
            val L2: Job = launch {
                println("testCancelJoinTimeOut >> Launch2 ${Thread.currentThread()} L2 Hello")
            }
            var a2 = async {
                repeat(20) {
                    println("testCancelJoinTimeOut >> async2 ${Thread.currentThread()} $it A2 Good")
                    delay(200)
                    //Thread.sleep(1000)
                }
            }
            //a2.cancelAndJoin()//取消协程,并返回主协程
            // a2.join()//如此则必须 a2 结束协程,才会走下面的
            var a1 = async {
                println("testCancelJoinTimeOut >> async ${Thread.currentThread()} A1 Hello")
                //测试取消 a2
                a2.cancel()
            }
            println("testCancelJoinTimeOut ${Thread.currentThread()} Out")
        }
        println("函数总耗时 $time")
    }

  6.2 调用及输出结果

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

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

    /**
     * 5. time out
     * 执行超时抛出异常
     */
    private fun testTimeOut() = runBlocking {
        val time = measureTimeMillis {
            //超时自动取消内部协程,抛异常
            withTimeout(2000) {
//                repeat(200) {
//                    println("withTimeOut 的${Thread.currentThread()} $it")
//                    delay(300)
//                }
                launch {
                    repeat(200) {
                        println("withTimeOut中 launch 的 ${Thread.currentThread()} $it")
                        delay(300)
                    }
                }
                println("withTimeOut ${Thread.currentThread()}")
            }
            withTimeoutOrNull(1000) {
                println("withTimeoutOrNull ${Thread.currentThread()}")
            }
        }
        println("函数总耗时 -----  $time")
    }

  7.2 调用及输出结果

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

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

    /**
     * await,async的异步deferred结果获取
     */
    private fun testAwait() = runBlocking {
        val time: Long = measureTimeMillis {
            val a2 = async {
                println("testAwait ${Thread.currentThread()} A2 Good")
                delay(3000)
                100
            }
            //a2.join()
            val a1 = async {
                getA1()
            }
            //a1.join()
            println("result ${Thread.currentThread()} -- ${a1.await()} ${a2.await()}")
        }
        println("函数总耗时: $time")
    }
    //suspend fun 挂起函数
    private suspend fun getA1(): Int {
        println("testAwait>>async ${Thread.currentThread()} A1 Good")
        delay(2000)
        return 99
    }

  8.2 调用及输出结果

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hanyang Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值