我有一些任务需要连同三个步骤一起执行,第一步和第三步必须顺序运行,只有第二步同时运行,给出了Kotlin Channel遵循先进先出的顺序,我不能总是让Step 3顺序运行,有没有任何实现可以满足我的目的,或者另一种数据 struct ?
以下是我的演示代码:
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlin.random.Random
class SortingReceiveChannelTest(
private val coroutineScope: CoroutineScope
) {
private val tasks = List(30) { Task(it) }
private val randomDelay = Random(Int.MAX_VALUE)
private val step2Channel = Channel<Task>(2)
private val step3Channel = Channel<Task>()
fun start() {
coroutineScope.launch(Dispatchers.IO) {
for (task in tasks) {
task.step1()
step2Channel.send(task)
}
}
coroutineScope.launch(Dispatchers.IO) {
repeat(tasks.size) {
val task = step2Channel.receive()
coroutineScope.launch(Dispatchers.IO) {
task.step2()
step3Channel.send(task)
}
}
}
coroutineScope.launch(Dispatchers.IO) {
repeat(tasks.size) {
val task = step3Channel.receive()
task.step3()
}
}
}
inner class Task(val index: Int) {
fun step1() {
Log.i(TAG, "execute step1[$index] sequential")
// sleep to simulating a long run task
Thread.sleep(randomDelay.nextLong(100, 200))
// Log.i(TAG, "step1[$index] executed")
}
fun step2() {
Log.i(TAG, "execute step2[$index] concurrently")
if (index == 2 || index == 5 || index == 8 || index == 16) {
// make specific tasks run longer to mess the step3's order
Thread.sleep(randomDelay.nextLong(2000, 5000))
} else {
Thread.sleep(randomDelay.nextLong(100, 300))
}
// Log.i(TAG, "step2[$index] executed")
}
fun step3() {
Log.i(TAG, "execute step3[$index] sequential")
Thread.sleep(randomDelay.nextLong(100, 300))
// Log.i(TAG, "step3[$index] executed")
}
}
companion object {
private const val TAG = "SortChannel"
}
}