让队列并发执行任务1和任务2,当两个任务都执行完毕后回到主线程执行任务3:

    1. // 创建队列组
    2. dispatch_group_t group = dispatch_group_create();
    3. // 创建并发队列
    4. dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
    5. // 执行任务1
    6. dispatch_group_async(group, queue, ^{
    7. for (int i = 0; i < 3; i++) {
    8. NSLog(@"任务1 - %d - %@", i, [NSThread currentThread]);
    9. }
    10. });
    11. // 执行任务2
    12. dispatch_group_async(group, queue, ^{
    13. for (int i = 0; i < 3; i++) {
    14. NSLog(@"任务2 - %d - %@", i, [NSThread currentThread]);
    15. }
    16. });
    17. // 等前面的任务执行完毕后,会自动执行这个任务
    18. dispatch_group_notify(group, queue, ^{
    19. dispatch_async(dispatch_get_main_queue(), ^{
    20. for (int i = 0; i < 3; i++) {
    21. NSLog(@"任务3 - %d - %@", i, [NSThread currentThread]);
    22. }
    23. });
    24. });

    打印结果:

    1. ~: 任务2 - 0 - <NSThread: 0x600001ea43c0>{number = 6, name = (null)}
    2. ~: 任务1 - 0 - <NSThread: 0x600001ee2d40>{number = 4, name = (null)}
    3. ~: 任务2 - 1 - <NSThread: 0x600001ea43c0>{number = 6, name = (null)}
    4. ~: 任务1 - 1 - <NSThread: 0x600001ee2d40>{number = 4, name = (null)}
    5. ~: 任务2 - 2 - <NSThread: 0x600001ea43c0>{number = 6, name = (null)}
    6. ~: 任务1 - 2 - <NSThread: 0x600001ee2d40>{number = 4, name = (null)}
    7. ~: 任务3 - 0 - <NSThread: 0x600001ef8280>{number = 1, name = main}
    8. ~: 任务3 - 1 - <NSThread: 0x600001ef8280>{number = 1, name = main}
    9. ~: 任务3 - 2 - <NSThread: 0x600001ef8280>{number = 1, name = main}

    dispatch_group_notify方法的作用就是监听group中的任务执行结束。