Kotlin协程(2)

传统异步的缺陷

线程是系统资源,不能很好支持高并发。
回调会产生回调地域。
Rx方式,其实很好,但是要记忆很多很多操作符,记不下那么多。

然后Kotlin协程来了

fun postItem(item: Item) {
    launch (CommonPool) {   //显性协程上下文
        val taken = preparePost()
        val post - submitPost(token, item)
        processPost(post)
    }
}

suspend fun preparePost() : Token {
    return suspendCoroutine {//....}
}

编译器会怎么做?

suspend fun submitPost(token: Token, item: Item) {
    //...
}

//编译后
Object submitPost(Token token, Item item, Continuation<Post> cont){
    //...
}
public interface Continuation<in T>{
    public val context: CoroutineContext
    public fun resume(value: T)
    public fun resumeWithException(ex: Throwable)
}

//内部状态机
switch (cont.label){
    case 0:
        cont.label = 1;
        preparePost(cont)
        break;
    case 1:
        Token token = (Token) prevResult;
        cont.label = 2;
        submitPost(token, item, cont);
    case 2:
        Post post = (Post) prevResult;
        processPost(post);
}

特别轻量

//main()是协程实现的
fun main(args: Array<String>) = runBlocking {
    val jobs = List(100000){ //100000个
        launch(CommonPool) { 
            delay(1000)      //在延迟1秒内启动别的协程
        }
    }
    jobs.forEach { it.join() }
}

//launch和async的区别在于后者有返回值
fun doSth() = async(CommonPool) {
    //...
}
val request = doSth()
request.wait()

await

val str = await(work()) //String result
//work()的返回值是CompletableFuture<String>


suspend fun <T> await(f: CompletableFuture<T>): T{
    suspendCoroutine { c ->
        f.whenComplete { value, ex ->
            if (ex != null) c.resumeWithException(ex)
            else c.resume(value)
        }
    }
}

通讯和同步

  • Job:一个可完成和可取消的实体,用于代表一个协程
  • deferred:一个Future用于,suspend函数的await()
  • Mutex:with suspend fun lock
  • Channel:SendChannel 和 ReceiveChannel
    • RendezvousChannel:同步的集合地
    • ArrayChannel:固定大小的Buffer
    • LinkedListChannel:无限制
    • ConflatedChannel:只有最近的被发送的元素会被保留
  • BroadCastChannel:可以被多个订阅,都能收到

协程建造器

  • launch
  • async
  • future
  • runBlocking
  • actor/produce: 通过Channel消费生产消息
  • publish
  • rxCompletable, rxSingle, rxObservable, rxFlowable

其他

顶层函数
  • select:支持CSP风格的编程
  • delay:延迟一定时间
  • await:
public suspend fun <T> java.util.concurrent.CompletableFuture<T>.await(): T { /* compiled code */ }

public suspend fun <T> java.util.concurrent.CompletionStage<T>.await(): T { /* compiled code */ }
  • aRead(), aWrite(): 用于AsynchronousXxxChannel在NIO
  • withTimeout:超时返回
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值