Kotlin中的ExecutiorService模拟程序



我有一段使用ExecutorService的Java代码。我需要使用协程将此代码转换为Kotlin。我尝试使用GlobalScope.lonch((,它确实有效,但非常不同。在Java代码中,有EXECUTOR_SERVICE.shutdown((和EXECUTO_SERVICE.awaitTermination来确定何时完成所有任务。在Kotlin最接近的实现是什么?

Java代码:

final ExecutorService EXECUTOR_SERVICE =
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for (int d = MIN_DEPTH; d <= maxDepth; d += 2) {
final int depth = d;
EXECUTOR_SERVICE.execute(() -> {
int check = 0;
final int iterations = 1 << (maxDepth - depth + MIN_DEPTH);
for (int i = 1; i <= iterations; ++i) {
final TreeNode treeNode1 = bottomUpTree(depth);
check += treeNode1.itemCheck();
}
results[(depth - MIN_DEPTH) / 2] =
iterations + "t trees of depth " + depth + "t check: " + check;
});
}
EXECUTOR_SERVICE.shutdown();
EXECUTOR_SERVICE.awaitTermination(120L, TimeUnit.SECONDS);

Kotlin没有将线程池与工作完成联系起来,但您的解决方案已经是一个准确的转换。你不需要做任何特别的事情来等待任务完成;这是由CCD_ 1和作为结构化并发的结果的每个协程生成器方法自动完成的。

我会把它写成

val result : List<Int> = runBlocking {
// you can specify a thread pool, but it looks like you should really use the default one
(MIN_DEPTH..maxDepth step 2).map { depth ->
async {
val check = 0
val iterations = 1 shl (maxDepth - depth + MIN_DEPTH)
for (i in 0 until iterations) {
check += bottomUpTree(depth).itemCheck()
}
check
}
}.awaitAll()
}

最新更新