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<Result<out Any>> {
    return CompletableFuture.supplyAsync({ Result.of(Head()) }, executor::execute)
}
//异步获取Body
fun getBody(): CompletableFuture<Result<out Any>> {
    return CompletableFuture.supplyAsync({ Result.of(Body()) }, executor::execute)
}
//异步获取Foot
fun getFoot(): CompletableFuture<Result<out Any>> {
    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 <T> sequence(futures: List<CompletableFuture<T>>): CompletableFuture<List<T>> {
        return CompletableFuture.allOf(*futures.toTypedArray()).thenApply { futures.map { it.join() } }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,903评论 1 32
  • 这部分主要是开源Java EE框架方面的内容,包括Hibernate、MyBatis、Spring、Spring ...
    杂货铺老板阅读 5,338评论 0 2
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 14,310评论 3 20
  • 前端开发面试题 面试题目: 根据你的等级和职位的变化,入门级到专家级,广度和深度都会有所增加。 题目类型: 理论知...
    怡宝丶阅读 7,410评论 0 7
  • 对于开发人员来说,设计模式有时候就是一道坎,但是设计模式又非常有用,过了这道坎,它可以让你水平提高一个档次。而在a...
    WANKUN阅读 2,187评论 0 2

友情链接更多精彩内容