kotlin协程
companion object {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val p = StringBuilder()
p.append("1")
var list = ArrayList<String>()
println("""开始""")
println("" + list!!.size)
println("" + list?.size)
launch {
val a = GlobalScope.launch {
val thread1 = withContext(Dispatchers.IO) {
println("thread1" + Thread.currentThread().name)
Thread.sleep(1000)
}
val thread2 = withContext(Dispatchers.Unconfined) {
println("thread2" + Thread.currentThread().name)
}
}
val b = async {
Thread.sleep(5000)
println("async run")
}
a.join()
println("I m done")
}
println("finish")
}
}
创建两个协程 a ,b a有两个子耗时的suspend函数
async{}是可以开启一个异步协程的,相对于launch{},async{}返回的是带返回值的Job,public interface Deferred : Job T就是返回值,通过await获得该返回值。
launch{
val a = async{ 耗时1s …}.await();
val b = async{ 耗时5s …}.await();
}
}
后续继续学习补充