什么是GCD
GCD是一种异步执行任务的技术。开发者只需要将想要执行的任务添加到适当的Dispatch Quere中,GCD就能生成必要的线程并执行任务。
GCD相比NSThread类等的多线程方法,更加简洁和一目了然,并且GCD可以提供系统级别的线程管理来提高执行效率。
还会自动管理线程的生命周期,如:创建线程、调度任务、销毁线程。
使用方式
- 创建队列
- 派遣任务(同步、异步)
同步与异步
同步:在当前线程中执行
异步:在其他线程中执行
串行队列
按顺序,一个任务一个任务顺序执行。
串行同步:
//创建队列
dispatch_queue_t queue = dispatch_queue_create("com.leshipi.text.timeConsumingOperation", DISPATCH_QUEUE_SERIAL);
//队列类型:串行:DISPATCH_QUEUE_SERIAL
//队列特征:按队列添加顺序执行
//派遣任务(同步)
for (int i = 0; i < 10; i++) {
dispatch_sync(queue, ^{
//耗时操作
NSLog(@"%@ - %d",[NSThread currentThread],i);
});
}
串行同步运行结果:
2021-11-25 19:35:22.924951+0800 text2021[34027:3529757] <NSThread: 0x600003c6c940>{
number = 1, name = main} - 0
2021-11-25 19:35:22.925199+0800 text2021[34027:3529757] <NSThread: 0x600003c6c940>{
number = 1, name = main} - 1
2021-11-25 19:35:22.925398+0800 text2021[34027:3529757] <NSThread: 0x600003c6c940>{
number = 1, name = main} - 2
2021-11-25 19:35:22.925563+0800 text2021[34027:3529757] <NSThread: 0x600003c6c940>{
number = 1, name = main} - 3
2021-11-25 19:35:22.925756+0800 text2021[34027:3529757] <NSThread: 0x600003c6c940>{
number = 1, name = main} - 4
2021-11-25 19:35:22.925906+0800 text2021[34027:3529757] <NSThread: 0x600003c6c940>{
number = 1, name = main} - 5
2021-11-25 19:35:22.926067+0800 text2021[34027:3529757] <NSThread: 0x600003c6c940>{
number = 1, name = main} - 6
2021-11-25 19:35:22.926220+0800 text2021[34027:3529757] <NSThread: 0x600003c6c940>{
number = 1, name = main} - 7
2021-11-25 19:35:22.926397+0800 text2021[34027:3529757] <NSThread: 0x600003c6c940>{
number = 1, name = main} - 8
2021-11-25 19:35:22.926543+0800 text2021[34027:3529757] <NSThread: 0x600003c6c940>{
number = 1, name = main} - 9
串行异步:
//创建队列
dispatch_queue_t queue = dispatch_queue_create("com.leshipi.text.timeConsumingOperation", DISPATCH_QUEUE_SERIAL);
//队列类型:串行:DISPATCH_QUEUE_SERIAL
//队列特征:按队列添加顺序执行
//派遣任务(异步)
for (int i = 0; i < 10; i++) {
dispatch_async(queue, ^{
//耗时操作
NSLog(@"%@ - %d",[NSThread currentThread],i);
});
}
串行异步运行结果:
2021-11-25 19:40:40.087646+0800 text2021[34107:3537423] <NSThread: 0x6000013b8500>{
number = 6, name = (null)} - 0
2021-11-25 19:40:40.087883+0800 text2021[34107:3537423] <NSThread: 0x6000013b8500>{
number = 6, name = (null)} - 1
2021-11-25 19:40:40.088256+0800 text2021[34107:3537423] <NSThread: 0x6000013b8500>{
number = 6, name = (null)} - 2
2021-11-25 19:40:40.088584+0800 text2021[34107:3537423] <NSThread: 0x6000013b8500>{
number = 6, name = (null)} - 3
2021-11-25 19:40:40.088754+0800 text2021[34107:3537423] <NSThread: 0x6000013b8500>{
number = 6, name = (null)} - 4
2021-11-25 19:40:40.088927+0800 text2021[34107:3537423] <NSThread: 0x6000013b8500>{
number = 6, name = (null)} - 5
2021-11-25 19:40:40.089115+0800 text2021[34107:3537423] <NSThread: 0x6000013b8500>{
number = 6, name = (null)} - 6
2021-11-25 19:40:40.089712+0800 text2021[34107:3537423] <NSThread: 0x6000013b8500>{
number = 6, name = (null)} - 7
2021-11-25 19:40:40.090308