GCD多线程dispatch_group当有异步任务执行要使用dispatch_group_enter和dispatch_group_leave

 dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_group_async(group, dispatch_get_main_queue(), ^{
        NSLog(@"任务1完成");
        dispatch_group_leave(group);
    });
    
    dispatch_group_enter(group);
    dispatch_group_async(group, dispatch_get_main_queue(), ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"任务2完成");
            dispatch_group_leave(group);
        });
        
    });
    
    dispatch_group_enter(group);
    dispatch_group_async(group, dispatch_get_main_queue(), ^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"任务3完成");
            dispatch_group_leave(group);
        });
    });
    
     dispatch_group_enter(group);
    dispatch_group_async(group, dispatch_get_main_queue(), ^{
        
        NSLog(@"任务4完成");
        dispatch_group_leave(group);
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"所有的任务都完成");
    });

打印输出

2018-07-25 18:07:04.563230+0800 CoreAnimationLearn[21466:335204] 任务1完成
2018-07-25 18:07:04.564509+0800 CoreAnimationLearn[21466:335204] 任务4完成
2018-07-25 18:07:06.564657+0800 CoreAnimationLearn[21466:335204] 任务3完成
2018-07-25 18:07:07.841039+0800 CoreAnimationLearn[21466:335204] 任务2完成
2018-07-25 18:07:07.841257+0800 CoreAnimationLearn[21466:335204] 所有的任务都完成

ps:dispatch_group队列里面的任务还是异步执行的

你可能感兴趣的:(GCD多线程dispatch_group当有异步任务执行要使用dispatch_group_enter和dispatch_group_leave)