协程概念
协程首先不是一个线程或者进程,是一个新的概念,不可以用线程或者进程混淆,可以理解为具有挂起功能的函数调用(因为携程可以在自己控制切换上下文)
kotlin中协程大多指的是在kotlinx.coroutines扩展包中的携程库
协程的启动方式
协程的启动方式
1·GlobalScope.launch
GlobalScope:A global CoroutineScope not bound to any job.
没有绑定任何协程作用域的协程
launch:Launches a new coroutine without blocking the current thread
启动一个不阻塞线程的协程
使用方式如下:
GlobalScope.launch {
//执行代码块
}
2·runBlocking
Runs a new coroutine and blocks the current thread interruptibly until its completion
启动一个直到执行完毕都会阻塞当前线程的协程
使用代码如下
fun doCoroutine()=runBlocking {
//执行代码块
}
fun doCoroutine(){
runBlocking {
//执行代码块
}
}
3·CoroutineScope.launch
Launches a new coroutine without blocking the current thread
启动一个不阻塞线程的协程
但是由于该方法是CoroutineScope的扩展函数,所以一般在协程作用域中可以直接调用launch启动,一般用于子携程或者当前作用域协程,可以理解GlobalScope.launch 是该方法的特殊扩展方法,相当于子类的launch方法
fun doCoroutine()=runBlocking {
launch{
}
}
public fun CoroutineScope.launch(_,_,_): Job {
...
return coroutine
}
public object GlobalScope : CoroutineScope {
/**
* Returns [EmptyCoroutineContext].
*/
override val coroutineContext: CoroutineContext
get() = EmptyCoroutineContext
}
4·coroutineScope{} 和 CoroutineScope()
先看runBlocking的入参和launch的入参(省略版)
public fun <T> runBlocking(_, block: suspend CoroutineScope.() -> T): T {
val coroutine = BlockingCoroutine<T>(newContext, currentThread, eventLoop)
coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
return coroutine.joinBlocking()
}
public fun CoroutineScope.launch(_, _, block: suspend CoroutineScope.() ->Unit): Job {
coroutine.start(start, coroutine, block)
return coroutine
}
block在两个函数入参中都是一个CoroutineScope的扩展方法,所以coroutineScope{}是在协程作用域中当构建器用的
代码执行方法
fun doCoroutine()=runBlocking {
coroutineScope{
}
}
CoroutineScope(EmptyCoroutineContext).launch { }
还有几种以后再说
关键字 suspend
suspend关键字使用来标识协程方法的前缀
所有因为在launch和runBlocking的入参block中都被suspend修饰了,所以可以理解为一个在协程作用域中执行的方法都需要被suspend修饰。
fun doCoroutine() = runBlocking {
launch (block = block)
coroutineScope(block = block)
}
var block: suspend CoroutineScope.() -> Unit =
{
}
Job 任务管理
通过GlobalScope.launch 或者runblocking创建的协程都会返回一个Job类型,Job是给协程使用者提供管理协程的封装体,包括启动,取消等等操作这里就不一一记录
Dispatchers 协程调度器
Dispatchers.Default
默认调度 它由JVM上的共享线程池支持。默认情况下,此调度程序使用的最大并行级别等于CPU内核数,至少为两个( 机翻)
Dispatchers.Main
主线程
Dispatchers.IO
任务线程 和Default 公用一个线程池
newSingleThreadContext
独立线程,最好能管理生命周期
Unconfined
用于嵌套调度,类似想做个递归(求大神指点)
启动模式
launch的start参数 有四种类型
DEFAULT
默认,不传或传入此参数会立即执行协程
LAZY
launch后不立即执行,需要获取其job发起执行
ATOMIC
执行前不可取消的
UNDISPATCHED
在当前线程立即执行
使用方法
runBlocking {
launch ( CoroutineStart.DEFAULT)
}
以上都是协程的基本概念
网友评论