Job:协程构建函数的返回值,可以把 Job 看成协程对象本身,包含了对协程的控制方法。
Deffered是Job的子类,实际上就增加了个await方法。能够让当前协程暂时挂起,暂停往下执行。当await方法有返回值后,会恢复协程,继续往下执行
方法 | 说明 |
---|---|
start() | 手动启动协程 |
join() | 等待协程执行完毕 |
cancel() | 取消一个协程 |
协程的启动
public fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job{
val newContext = newCoroutineContext(context)
val coroutine = StandaloneCoroutine(newContext, active = true)
coroutine.start(start, coroutine, block)
}
CoroutineContext - 可以理解为协程的上下文,是一种key-value数据结构
CoroutineContext | List |
---|---|
get(key: Key): E | get(int index) |
plus(context: Element) | add(int index, E element) |
minusKey(key: Key<*>) | remove(E element) |
一个简单的例子
object CoroutineScene {
private const val TAG = “CoroutineScene”
fun startScene1(){
GlobalScope.launch (Dispatchers.Main){
Log.i(TAG,“startScene work on ${Thread.currentThread().name}”)
val result1 = request1()
val result2 = request2(result1)
val result3 = request3(result2)
updateUI(result3)
}
}
fun startScene2(){
GlobalScope.launch (Dispatchers.Main){
Log.i(TAG,“startScene work on ${Thread.currentThread().name}”)
val result1 = request1()
val deferred2 = GlobalScope.async { request2(result1) }
val deferred3 = GlobalScope.async { request3(result1) }
//不能单独调用await
updateUI(deferred2.await(),deferred3.await())
}
}
private fun updateUI(result: String) {
Log.i(TAG,“updateUI work on ${Thread.currentThread().name}”)
Log.i(TAG,“result: $result”)
}
private fun updateUI(result2:String,result3: String) {
Log.i(TAG,“updateUI work on ${Thread.currentThread().name}”)
Log.i(TAG,“result:
r
e
s
u
l
t
2
−
−
{result2}--
result2−−{result3}”)
}
//suspend 关键字的作用?
//delay既然是IO异步任务,是如何做到延迟协程中的代码向下执行的?
suspend fun request1():String{
delay(2*1000) //延迟2秒,不会暂停线程,但会暂停当前的协程
Log.i(TAG,“request1 work on ${Thread.currentThread().name}”)
return “result from request1”
}
suspend fun request2(request:String):String{
delay(2*1000) //延迟2秒
Log.i(TAG,“request2 work on ${Thread.currentThread().name}”)
return “result from request2”
}
suspend fun request3(request:String):String{
delay(2*1000) //延迟2秒
Log.i(TAG,“request3 work on ${Thread.currentThread().name}”)
return “result from request3”
}
}
CoroutineDispatcher 协程运行的线程调度器
协程调度器
模式 | 说明 |
---|---|
Dispatchers.IO | 显示指定协程运行的线程,为IO线程 |
Dispatchers.Main | 指定这个协程运行在主线程 |
Dispatchers.Default | 默认的,启动携程时会启动一个线程 |
Dispatchers.Unconfined | 不指定,就是在当前线程运行,协程恢复后的运行的线程取决于协程挂起时所在的线程 |
CoroutineStart - 启动模式
默认是DEAFAULT,也就是创建就启动;还有一个是LAZY,意思是等你需要它的时候,再调用启动
模式 | 说明 |
---|---|
CoroutineStart().DEAFAULT | 模式模式,创建即启动协程,可随时取消 |
ATOMIC | 自动模式,同样创建即启动,但启动前不可取消 |
LAZY | 延迟启动模式,只有当调用start方法时才会启动 |
3.协程挂起,恢复原理逆向剖析
挂起函数
被关键字suspend
修饰的方法在编译阶段,编译器会修改方法的签名.包括返回值,修饰符,入参,方法体实现。协程的挂起是靠挂起函数中实现的代码。
//kotlin
suspend fun request(): String {
delay(2 * 1000) //suspend fun()
println(“after delay”)
return “result from request”
}
转成java之后
//java
public static final Object request(Continuation completion) {
ContinuationImpl requestContinuation = completion;
if ((completion.label & Integer.MIN_VALUE) == 0)
requestContinuation = new ContinuationImpl(completion) {
@Override
Object invokeSuspend(Object o) {
label |= Integer.MIN_VALUE;
return request(this); //3.重新再次请求
}
};
}
switch (requestContinuation.label) {
case 0: { //1.第一次进来,执行方法,并且将标记改为1
requestContinuation.label = 1;
//2. 执行延迟操作,并将异步监听放进去,由此可见:协程的挂起其实是方法的挂起
Object delay = DelayKt.delay(2000, requestContinuation);
if (delay == COROUTINE_SUSPENDED) {
return COROUTINE_SUSPENDED;
}
}
}
//4.执行下面的方法
System.out.println(“after delay”)
return “result from request”;
}
协程挂起与协程恢复
协程的核心是挂起----恢复,挂起–恢复的本质是return & callback回调
模拟挂起和恢复的整个流程
object CoroutineScene2 {
private val TAG :String = “CoroutineScene2”
suspend fun request2():String{
delay(2*1000);
Log.i(TAG,“request2 completed”)
return “result from request2”;
}
}
Java
public class CoroutineScene2_decompiled {
private static final String TAG = “CoroutineScene2”;
//1.挂起流程
public static final Object request2(Continuation preCallback) {
ContinuationImpl request2Callback;
if (!(preCallback instanceof ContinuationImpl) || (((ContinuationImpl) preCallback).label & Integer.MAX_VALUE) == 0) {
request2Callback = new ContinuationImpl(preCallback) {
@Override
public Object invokeSuspend(@NotNull Object resumeResult) {
this.result = resumeResult;
this.label |= Integer.MAX_VALUE;
return request2(this);
}
};
} else {
request2Callback = (ContinuationImpl) preCallback;
}
switch (request2Callback.label){
case 0:
Object delay = DelayKt.delay(2000,request2Callback);
if(delay == IntrinsicsKt.getCOROUTINE_SUSPENDED()){
return IntrinsicsKt.getCOROUTINE_SUSPENDED();
}
}
Log.i(TAG,“request2 comleted”);
return “result from request 2”;
}
static abstract class ContinuationImpl implements Continuation {
Continuation preCallback;
int label;
Object result;
public ContinuationImpl(Continuation preCallback) {
this.preCallback = preCallback;
}
@NotNull
@Override
public CoroutineContext getContext() {
return preCallback.getContext();
}
//2.恢复流程
@Override
public void resumeWith(@NotNull Object result) {
Object suspend = invokeSuspend(result);
if(suspend == IntrinsicsKt.getCOROUTINE_SUSPENDED()){
return;
}
preCallback.resumeWith(suspend);
}
public abstract Object invokeSuspend(@NotNull Object resumeResult);
}
}
kotliin
object CoroutineScene2 {
private val TAG :String = “CoroutineScene2”
suspend fun request1():String{
val request2 :String = request2();
return “result from request1” + request2
}
suspend fun request2():String{
delay(2*1000);
Log.i(TAG,“request2 completed”)
return “result from request2”;
}
}
Java
public class CoroutineScene2_decompiled {
private static final String TAG = “CoroutineScene2”;
//1.挂起流程
public static final Object request1(Continuation preCallback) {
ContinuationImpl request1Callback;
if (!(preCallback instanceof ContinuationImpl) || (((ContinuationImpl) preCallback).label & Integer.MAX_VALUE) == 0) {
request1Callback = new ContinuationImpl(preCallback) {
@Override
public Object invokeSuspend(@NotNull Object resumeResult) {
this.result = resumeResult;
this.label |= Integer.MAX_VALUE;
Log.i(TAG,“request1 has resumed”);
return request1(this);
}
};
} else {
request1Callback = (ContinuationImpl) preCallback;
}
switch (request1Callback.label){
case 0:
//Object delay = DelayKt.delay(2000,request2Callback);
Object request2= request2(request1Callback);
if(request2 == IntrinsicsKt.getCOROUTINE_SUSPENDED()){
Log.i(TAG,“request1 has suspended”);
return IntrinsicsKt.getCOROUTINE_SUSPENDED();
}
}
Log.i(TAG,“request2 completed”);
return "result1 from request1 " + request1Callback.result;
}
//1.挂起流程
public static final Object request2(Continuation preCallback) {
ContinuationImpl request2Callback;
if (!(preCallback instanceof ContinuationImpl) || (((ContinuationImpl) preCallback).label & Integer.MAX_VALUE) == 0) {
request2Callback = new ContinuationImpl(preCallback) {
@Override
public Object invokeSuspend(@NotNull Object resumeResult) {
this.result = resumeResult;
this.label |= Integer.MAX_VALUE;
Log.i(TAG,“request2 has resumed”);
return request2(this);
}
};
} else {
request2Callback = (ContinuationImpl) preCallback;
}
switch (request2Callback.label){
case 0:
Object delay = DelayKt.delay(2000,request2Callback);
if(delay == IntrinsicsKt.getCOROUTINE_SUSPENDED()){
Log.i(TAG,“request2 has suspended”);
return IntrinsicsKt.getCOROUTINE_SUSPENDED();
}
}
Log.i(TAG,“request2 comleted”);
return “result from request 2”;
}
static abstract class ContinuationImpl implements Continuation {
Continuation preCallback;
int label;
Object result;
public ContinuationImpl(Continuation preCallback) {
this.preCallback = preCallback;
总结
最后为了帮助大家深刻理解Android相关知识点的原理以及面试相关知识,这里放上相关的我搜集整理的24套腾讯、字节跳动、阿里、百度2019-2021面试真题解析,我把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包知识脉络 + 诸多细节。
还有 高级架构技术进阶脑图、Android开发面试专题资料 帮助大家学习提升进阶,也节省大家在网上搜索资料的时间来学习,也可以分享给身边好友一起学习。
网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。
2021年虽然路途坎坷,都在说Android要没落,但是,不要慌,做自己的计划,学自己的习,竞争无处不在,每个行业都是如此。相信自己,没有做不到的,只有想不到的。祝大家2021年万事大吉。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!
[外链图片转存中…(img-0yR8DQVK-1715848474376)]
[外链图片转存中…(img-pWVZfR4a-1715848474378)]
网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。
2021年虽然路途坎坷,都在说Android要没落,但是,不要慌,做自己的计划,学自己的习,竞争无处不在,每个行业都是如此。相信自己,没有做不到的,只有想不到的。祝大家2021年万事大吉。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!