需要解决这个首先就需要了解dispatch_group_enter 和 dispatch_group_leave。
dispatch_group_enter 标志着一个任务追加到 group,执行一次,相当于 group 中未执行完毕任务数+1
dispatch_group_leave 标志着一个任务离开了 group,执行一次,相当于 group 中未执行完毕任务数-1。
当 group 中未执行完毕任务数为0的时候,才会使dispatch_group_wait解除阻塞,以及执行追加到dispatch_group_notify中的任务。
dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
[self requestA:^{
NSLog(@"---执行A任务结束---");
dispatch_group_leave(group);
}];
dispatch_group_enter(group);
[self requestB:^{
NSLog(@"---执行B任务结束---");
dispatch_group_leave(group);
}];
dispatch_group_enter(group);
[self requestC:^{
NSLog(@"---执行C任务结束---");
dispatch_group_leave(group);
}];
dispatch_group_notify(group, globalQueue, ^{
[self requestD:^{
NSLog(@"---执行D任务结束---");
}];
});
- (void)requestA:(void(^)(void))block{
NSLog(@"---执行A任务开始---");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
block();
});
}
- (void)requestB:(void(^)(void))block{
NSLog(@"---执行B任务开始---");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
block();
});
}
- (void)requestC:(void(^)(void))block{
NSLog(@"---执行C任务开始---");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
block();
});
}
- (void)requestD:(void(^)(void))block{
NSLog(@"---执行D任务开始---");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
block();
});
}
网友评论