Kotlin 協程輕量 協程與執行緒對比

2021-10-17 04:24:28 字數 509 閱讀 9504

本例使用協程和執行緒兩個方式執行一段任務:

協程:任務是每秒列印出兩個*->,執行100_000個任務;

@test

fun testmet() = runblocking }}

println()

val end = system.currenttimemillis()

println("end time$end")

println("耗時:$")

}

測試耗時:1247ms

採用執行緒:

@test

fun testmet01() = runblocking .start()}}

println()

val end = system.currenttimemillis()

println("end time$end")

println("耗時:$")

}

測試耗時:15325ms

Kotlin協程筆記

會阻塞主線程,等待協程執行完,才會繼續執行主線程 不會阻塞主線程,返回job型別的物件 var job globalscope.launch 3 async 用於啟動乙個非同步協程任務,與launch用法基本一樣,不阻塞執行緒,區別在於 async的返回值是deferred,將最後乙個封裝成了該物件...

協程與執行緒

reference 協程不只在go語言中實現了,其實目前大部分語言都實現了自己的一套協程,包括c erlang python lua j ascript ruby等。相對於協程,你可能對程序和執行緒更為熟悉。程序一般代表乙個應用服務,在乙個應用服務中可以建立多個執行緒,而協程與程序 執行緒的概念不一...

協程巢狀協程

import asyncio import functools 第三層協程 async def test1 print 我是test1 await asyncio.sleep 1 print test1已經睡了1秒 await asyncio.sleep 3 print test1又睡了3秒 ret...