如何将Java线程转换为Kotlin Coroutines?
我有一段“丑陋”的 Java 代码,需要转换为 Kotlin 惯用的协程,但我不太清楚如何转换。
Thread[] pool=new Thread[2*Runtime.getRuntime().availableProcessors()];
for (int i=0;i<pool.length;i++)
pool[i]=new Thread(){
public void run() {
int y; while((y=yCt.getAndIncrement())<out.length) putLine(y,out[y]);
}
};
for (Thread t:pool) t.start();
for (Thread t:pool) t.join();
我认为可以使用 runBlocking 来实现,但是如何处理 availableProcessors 计数?
I have this "ugly" Java code I need to convert to Kotlin idiomatic coroutines and I cant quite figure out how.
Thread[] pool=new Thread[2*Runtime.getRuntime().availableProcessors()];
for (int i=0;i<pool.length;i++)
pool[i]=new Thread(){
public void run() {
int y; while((y=yCt.getAndIncrement())<out.length) putLine(y,out[y]);
}
};
for (Thread t:pool) t.start();
for (Thread t:pool) t.join();
I think it is possible to implement using runBlocking but how do I deal with availableProcessors count?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将在此处做一些假设:
putline()
是CPU密集型而不是IO操作。我认为这是因为它使用2 * CPU内核的线程执行,通常用于CPU密集型任务。out
中的每个项目执行putline()
。从上面的代码中,尚不清楚egyct
最初是0
。OUT
不像数百万个项目那样大。然后,解决方案真的很容易:
几个解释的单词:
deptagter.default
coroutine dispatcher专门用于CPU计算,其线程数量取决于CPU内核的数量。我们不需要创建自己的线程,因为Coroutines提供合适的线程池。coroutinescope()
等待其孩子,因此我们不需要手动等待所有异步任务。在所有任务完成时,将执行coroutinesCope()
下方的任何代码。Java/线程与Kotlin/Coroutines代码之间的行为存在一些差异:
dispatchers.default
默认情况下具有螺纹= CPU内核的数量,而不是2 * CPU内核。I'll make some assumptions here:
putLine()
is a CPU intensive and not IO operation. I assume this, because it is executed using threads number of 2 * CPU cores, which is usually used for CPU intensive tasks.putLine()
for each item inout
. From the above code it is not clear if e.g.yCt
is initially0
.out
isn't huge like e.g. millions of items.Then the solution is really very easy:
Few words of explanation:
Dispatchers.Default
coroutine dispatcher is used specifically for CPU calculations and its number of threads depends on the number of CPU cores. We don't need to create our own threads, because coroutines provide a suitable thread pool.coroutineScope()
waits for its children, so we don't need to also manually wait for all asynchronous tasks. Any code put belowcoroutineScope()
will be executed when all tasks finish.There are some differences in behavior between the Java/threads and Kotlin/coroutines code:
Dispatchers.Default
by default has the number of threads = CPU cores, not 2 * CPU cores.