我一直在尝试实现 wait
&notifyAll
系统就像我以前在Java中所做的一样。主要思想是制作多个功能来等待信号并继续执行。
以下测试案例包装了预期的实现:
@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中的Coroutines进行操作?到目前为止还没有运气研究。
预先感谢。
是的。使您的所有功能都可以悬挂,然后从启动块中调用所有功能。就像这样
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