void main() {
String getName() {
print('bob');
return 'bob';
}
Future(() => print('Future'));
Future.value(getName()).then((value) {
scheduleMicrotask(() => print('micro'));
print('then1');
}).then((value) => print('then2'));
}
学习之前,先来一张图, 程序运行后,打印内容是什么?打印顺序是什么?
flutter的异步操作不等于java的多线程,更贴近JS的单线程。
dart的线程是每个都封装在【lsolate】的盒子里,互相不共享内存,不共享变量,垃圾回收机制十分高效。【一般情况下一个线程就够用了】
同步运行代码:
//todo 直接运行
Future.sync(() => print('Future 1'));
Future.value(getName());
单进程一般用来等待事件发生,如果要处理大型数据等是无法解决的,需要lsolate。
事件循环(Event Loop)
eventLoop会不停循环查看EventQueue【事件队列】,异步操作就是往Queue添加事件。
//todo event
Future(() => print('event 1'));
//delayed是有一个计时器完结后再添加到队列里
//Duration.zero()这句代码是很快的意思,可以换成Duration(时间)
Future.delayed(Duration.zero,()=> print('event 2'));
event1和event2直接添加到EventQueue挂起,main运行完了,就开始访问eventQueue,然后执行event1和event2。
还有个VIP的队列(Microtask Queue)
//todo MicroTask
scheduleMicrotask(() => print('---------micro 1'));
Future.microtask(() => print('---------micro 2'));
Future.value(123).then((value) => print('---------micro 3'));
main运行完后,优先查看Microtask的队列,Micrtotask队列没有事件以后,再去检查event的队列。
如果在执行event事件的同时,Microtask又新加了任务,那么当前事件结束,优先去执行Microtask事件。
也就是说,Microtask没有任务就执行event,有任务就第一时间处理Microtask。不过一般情况下不会使用Microtask,如果大家都使用此线程,就没有优先级可说了。
总结:
打开程序=》main()=》Microtask(有任务)=》处理Microtask任务=》Microtask(无任务)=》
EventQueue=》处理event=》检查Microtask是否有任务=》如果都没有任务=》结束
--此图来源于王叔不秃B站视频,侵删。
最后的答案