kotlin-logo.jpeg
在学习 go 语言接触到 goroutine ,感觉非常好用,现在 kotlin 作为一门后起之秀当然不能错过这么 awesome 的特性
在java 我们对应 parallesim 来实现高并发,在 java 、c++ 和 c# 这些语言中更多的精力都话费处理线程间的资源共享所带来的条件竞争。高并发通过开线程进行并行处理,而在 coroutine 对应高并发是采用非阻塞的异步处理。
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.0-alpha-2'
协程并非线程,协程也无法代替线程。协程是通过框架代码实现的而非系统或虚拟机实现的。与之相反,线程/进程是需要虚拟机或操作系统的支持,通过调度CPU执行生效。
一个系统开的线程数量是有上线的,而且成本高昂,存在各种各样问题。如果我们需要非阻塞的异步编程,用线程来实现是难而贵。
import kotlinx.coroutines.*
fun main() {
GlobalScope.launch { // launch new coroutine in background and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello,") // main thread continues while coroutine is delayed
Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}
程序运行先打印 hello 然后 1 秒后打印 world 最后 2 秒后退出程序。
可能是go 最先实现的协程吧,现在风靡一时。协程就是一种轻量级的线程,这样解释可能并正确。
- lauch 来了一个协程,协程是有作用域的也就是他们有效时间,也可以理解为生命周期。这个作用域是 GlobalScope,从字面上理解也就是整个应用生命周期。
- 可以通过开线程来实现想同样效果
thread{...}
然后将delay()
替换为Thread.sleep(...)
- 注意这里 delay 是一个suspending fuction这是协程特有的。
fun main() = runBlocking<Unit> { // start main coroutine
GlobalScope.launch { // launch new coroutine in background and continue
delay(1000L)
println("World!")
}
println("Hello,") // main coroutine continues here immediately
delay(2000L) // delaying for 2 seconds to keep JVM alive
}
fun main(args: Array<String>) = runBlocking<Unit>{
GlobalScope.launch { // launch new coroutine in background and continue
delay(1000L)
println("World!")
}
println("Hello,") // main coroutine continues here immediately
delay(2000L) // delaying for 2 seconds to keep JVM alive
}
fun main(args: Array<String>) = runBlocking<Unit>{
GlobalScope.launch { // launch new coroutine in background and continue
delay(1000L)
println("World!")
}
println("Hello,") // main coroutine continues here immediately
delay(2000L) // delaying for 2 seconds to keep JVM alive
}
interface ApiService {
fun getDataValue(value:String)
}
fun getValue(service: ApiService){
Thread(Runnable {
Thread.sleep(2000)
service.getDataValue("value")
}).start()
}
fun main(args: Array<String>) = runBlocking<Unit>{
var apiServer = object : ApiService {
override fun getDataValue(value: String) {
print(value)
}
}
getValue(apiServer)
}
suspend fun getAsyncValue():String{
delay(1000)
return "asyncValue"
}
fun main(args: Array<String>) {
// var apiServer = object : ApiService {
// override fun getDataValue(value: String) {
// print(value)
// }
// }
// getValue(apiServer)
runBlocking {
val job = async {
getAsyncValue()
}
println(job.await())
}
}
在 go 语言中 main 方法本身就是 goroutine,当在 main 方法开一个 goroutine 异步延时执行一些操作,这些操作可能需要在 main 方法中执行
fun main() = runBlocking {
val job = GlobalScope.launch { // launch new coroutine and keep a reference to its Job
delay(1000L)
println("World!")
}
println("Hello,")
job.join() // wait until child coroutine completes
}
Java-Vs-Kotlin-–-Which-Should-You-Choose-For-Android-Development.png