让队列并发执行任务1和任务2,当两个任务都执行完毕后回到主线程执行任务3:
// 创建队列组
dispatch_group_t group = dispatch_group_create();
// 创建并发队列
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
// 执行任务1
dispatch_group_async(group, queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"任务1 - %d - %@", i, [NSThread currentThread]);
}
});
// 执行任务2
dispatch_group_async(group, queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"任务2 - %d - %@", i, [NSThread currentThread]);
}
});
// 等前面的任务执行完毕后,会自动执行这个任务
dispatch_group_notify(group, queue, ^{
dispatch_async(dispatch_get_main_queue(), ^{
for (int i = 0; i < 3; i++) {
NSLog(@"任务3 - %d - %@", i, [NSThread currentThread]);
}
});
});
打印结果:
~: 任务2 - 0 - <NSThread: 0x600001ea43c0>{number = 6, name = (null)}
~: 任务1 - 0 - <NSThread: 0x600001ee2d40>{number = 4, name = (null)}
~: 任务2 - 1 - <NSThread: 0x600001ea43c0>{number = 6, name = (null)}
~: 任务1 - 1 - <NSThread: 0x600001ee2d40>{number = 4, name = (null)}
~: 任务2 - 2 - <NSThread: 0x600001ea43c0>{number = 6, name = (null)}
~: 任务1 - 2 - <NSThread: 0x600001ee2d40>{number = 4, name = (null)}
~: 任务3 - 0 - <NSThread: 0x600001ef8280>{number = 1, name = main}
~: 任务3 - 1 - <NSThread: 0x600001ef8280>{number = 1, name = main}
~: 任务3 - 2 - <NSThread: 0x600001ef8280>{number = 1, name = main}
dispatch_group_notify方法的作用就是监听group中的任务执行结束。