Err*_*r19 6 android coroutine kotlin kotlin-coroutines
据我了解,Dispatchers.IO 可以创建的最大线程数是 64,但我的结果有点棘手。
这是我的代码。
repeat(500) {
CoroutineScope(Dispatchers.IO).launch {
println(Thread.currentThread().name)
}
}
Run Code Online (Sandbox Code Playgroud)
这就是结果。
...
DefaultDispatcher-worker-18
DefaultDispatcher-worker-46
DefaultDispatcher-worker-17
DefaultDispatcher-worker-47
DefaultDispatcher-worker-69
DefaultDispatcher-worker-64
DefaultDispatcher-worker-66
DefaultDispatcher-worker-67
DefaultDispatcher-worker-68
DefaultDispatcher-worker-41
...
Run Code Online (Sandbox Code Playgroud)
为什么我的线程池数量大于 64?这是否意味着我实际创建的线程数超过 64 个?
感谢您的阅读!请帮我
我不知道 Dispachers.IO 如何命名它的线程,但我一次只能运行 64 个协程。
如果您想将其限制为您拥有的 CPU 数量,则需要设置此系统属性:kotlinx.coroutines.io.parallelism
fun main(args: Array<String>) {
class Counter {
private var current=0
private var max=0
fun addOne() {
synchronized(this) {
current++
max = Math.max(max,current)
}
}
fun subOne() {
synchronized(this) {
current--
}
}
fun getMax() = max
}
val counter=Counter()
val jobs = (0..500).map {
CoroutineScope(Dispatchers.IO).launch {
counter.addOne()
Thread.sleep(100)
counter.subOne()
}
}
var done = false
while(!done) {
val j = jobs.find{it.isActive}
if( j == null) {
done = true
} else {
Thread.sleep(100)
}
}
println("max = ${counter.getMax()}")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2209 次 |
| 最近记录: |