我正在启动几个协程,但有Dispatchers.IO.limitedParallelism(1)
个调度器,我希望他们一个接一个地执行.
@Test fun `testParallelism`(){
runBlocking {
val maxParallel = 1
val ctx =Dispatchers.IO.limitedParallelism(maxParallel)
val max = AtomicLong(Long.MIN_VALUE)
val counter = AtomicLong(0)
(0..1000).map {
CoroutineScope(ctx).launch(ctx) {
val c = counter.incrementAndGet()
max.set(Math.max(max.get(), c))
delay(100)
counter.decrementAndGet()
}
}.joinAll()
// max is 1000
assertTrue { max.get() <= maxParallel }
}
}
然而,在上面的代码中,断言失败了.看起来所有的协程都是同时启动的.把计数器升到1000
.
是不是我在测试代码中做错了什么,或者我对API的理解有误?