Kotlin下的CompletableFuture的编程一

我们需要要组成一个Person实体,由3个部分head,body,foot组成。
组成实体的每个组件,每一步都没有依赖,可以同时获取一同组装。

首先我们定义出Person实体和她都组成部分

inner class Head
inner class Body
inner class Foot
class Person {
    var head: Head? = null
    var body: Body? = null
    var foot: Foot? = null

    fun set(v: Any?) {
        when (v) {
            is Head -> this.head = v
            is Body -> this.body = v
            is Foot -> this.foot = v
            else -> println("not support type")
        }
    }
    override fun toString(): String {
        return "Person(head=$head, body=$body, foot=$foot)"
    }
}

然后我们开始异步拼装实体Person

//定义一个业务线程池
val executor = ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, LinkedBlockingQueue())
//异步获取Head
fun getHead(): CompletableFuture> {
    return CompletableFuture.supplyAsync({ Result.of(Head()) }, executor::execute)
}
//异步获取Body
fun getBody(): CompletableFuture> {
    return CompletableFuture.supplyAsync({ Result.of(Body()) }, executor::execute)
}
//异步获取Foot
fun getFoot(): CompletableFuture> {
    return CompletableFuture.supplyAsync({ Result.of(Foot()) }, executor::execute)
}

val futures = listOf(getHead(), getBody(), getFoot())
//获取3个组件完成,初始化一个Person对象,将组件拼接上去
val result = sequence(futures).get().fold(Result.of(Person())) { p, v -> p.model?.set(v.model);p }

println(result.model)

做一个工具方法获取全部的结果

fun  sequence(futures: List>): CompletableFuture> {
        return CompletableFuture.allOf(*futures.toTypedArray()).thenApply { futures.map { it.join() } }
}

你可能感兴趣的:(Kotlin下的CompletableFuture的编程一)