请问下面两个方法的打印结果是什么?
1 | // 案例1 |
1 | // 案例2 |
案例解析
1 | // 案例1打印输出 |
案例1: 很好理解 队列中的线程按顺序执行
案例2: 注意点是 队列是管理线程的, 而任务是放在线程中执行的
概念总结
1 队列和线程的区别:
队列:是管理线程的,相当于线程池,能管理线程什么时候执行。
队列分为串行队列和并行队列
串行队列:队列中的线程按顺序执行(不会同时执行)
并行队列:队列中的线程会并发执行,可能会有一个疑问,队列不是先进先出吗,如果后面的任务执行完了,怎么出去的了。这里需要强调下,任务执行完毕了,不一定出队列。只有前面的任务执行完了,才会出队列。
2 主线程队列和GCD创建的队列也是有区别的。
主线程队列和GCD创建的队列是不同的。在GCD中创建的队列优先级没有主队列高,所以在GCD中的串行队列开启同步任务里面没有嵌套任务是不会阻塞主线程,只有一种可能导致死锁,就是串行队列里,嵌套开启任务,有可能会导致死锁。
主线程队列中不能开启同步,会阻塞主线程。只能开启异步任务,开启异步任务也不会开启新的线程,只是降低异步任务的优先级,让cpu空闲的时候才去调用。而同步任务,会抢占主线程的资源,会造成死锁。
3 线程:里面有非常多的任务(同步,异步)
同步与异步的区别:
同步任务优先级高,在线程中有执行顺序,不会开启新的线程。
异步任务优先级低,在线程中执行没有顺序,看cpu闲不闲。在主队列中不会开启新的线程,其他队列会开启新的线程。
素材来源
- 本文作者: 醉疏狂
- 本文链接: https://hubin97.github.io/2023/10/08/一个串行同步问题/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!