协程:有没有办法阻止多个执行并通知所有执行?

时间:2019-05-08 12:27:49

标签: android asynchronous kotlin coroutine kotlin-coroutines

我一直试图像以前在Java中那样实现waitnotifyAll系统。主要思想是调用多个函数以等待信号并继续执行。

以下测试用例包装了预期的实现:

@Test
fun blocking_multiple_shouldReturnOne() {
    var valueOne : Int? = null
    var valueTwo : Int? = null
    var valueThree : Int? = null
    var valueFour : Int? = null

    val threadManager = ThreadManager()

    threadManager.startBlocking { 
        valueOne = 1
    }

    threadManager.startBlocking {
        valueTwo = 1
    }

    threadManager.startBlocking {
        valueThree = 1
    }

    threadManager.startBlocking {
        valueFour = 1
    }

    threadManager.startAndNotifyAll {
        valueOne = 0
        valueTwo = 0
        valueThree = 0
        valueFour = 0
    }

    assertTrue("startBlocking wasn't executed right after notify all", valueOne == 1)
    assertTrue("startBlocking wasn't executed right after notify all", valueTwo == 1)
    assertTrue("startBlocking wasn't executed right after notify all", valueThree == 1)
    assertTrue("startBlocking wasn't executed right after notify all", valueFour == 1)
}

有没有一种方法可以在Kotlin中使用协同程序?到目前为止,还没有运气研究。

谢谢。

1 个答案:

答案 0 :(得分:-1)

可以。使所有函数可挂起,然后从启动块中调用所有这些函数。 会是这样

suspend fun fun1() {
  println("some async 1")
}

suspend fun fun2() {
  println("some async 2")
}

suspend fun fun3() {
  println("some async 3")
}

CoroutineScope(Dispatchers.Default).launch {
    fun1()
    fun2()
    fun3()
}

结果将是

some async 1
some async 2
some async 3