我想跑一些踏板,等到所有的踏板都完成了,就会得到结果。
可能的方法是在下面的代码中实现。但是它是线程安全的吗?
import kotlin.concurrent.thread
sealed class Errorneous<R>
data class Success<R>(val result: R) : Errorneous<R>()
data class Fail<R>(val error: Exception) : Errorneous<R>()
fun <R> thread_with_result(fn: () -> R): (() -> Errorneous<R>) {
var r: Errorneous<R>? = null
val t = thread {
r = try { Success(fn()) } catch (e: Exception) { Fail(e) }
}
return {
t.join()
r!!
}
}
fun main() {
val tasks = listOf({ 2 * 2 }, { 3 * 3 })
val results = tasks
.map{ thread_with_result(it) }
.map{ it() }
println(results)
}附注:
在Kotlin中有没有更好的内置工具来做到这一点?比如处理10000个任务,有10个线程的池?
它应该是线程,而不是协程,因为它将与遗留代码一起使用,我不知道它是否与协程一起工作得很好。
发布于 2020-08-14 20:43:52
看起来Java有Executors可以做到这一点
fun <R> execute_in_parallel(tasks: List<() -> R>, threads: Int): List<Errorneous<R>> {
val executor = Executors.newFixedThreadPool(threads)
val fresults = executor.invokeAll(tasks.map { task ->
Callable<Errorneous<R>> {
try { Success(task()) } catch (e: Exception) { Fail(e) }
}
})
return fresults.map { future -> future.get() }
}https://stackoverflow.com/questions/63411285
复制相似问题