- dispatch_group_enter、dispatch_group_leave组合,等同于dispatch_group_async。
- dispatch_group_enter标志着一个任务追加到 group,执行一次,相当于 group 中未执行完毕任务数+1
- dispatch_group_leave标志着一个任务离开了 group,执行一次,相当于 group 中未执行完毕任务数-1。
#pragma mark dispatch_group_enter、dispatch_group_leave
- (void)gcd_dispatch_group_enter_leave {
//打印当前线程
NSLog(@"currentThread---%@",[NSThread currentThread]);
NSLog(@"group---begin");
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_enter(group);
dispatch_async(queue, ^{
// 追加任务1
for (int i = 0; i < 2; ++i) {
//模拟耗时操作
[NSThread sleepForTimeInterval:2];
//打印当前线程
NSLog(@"1---%@",[NSThread currentThread]);
}
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
// 追加任务2
for (int i = 0; i < 2; ++i) {
//模拟耗时操作
[NSThread sleepForTimeInterval:2];
//打印当前线程
NSLog(@"2---%@",[NSThread currentThread]);
}
dispatch_group_leave(group);
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//等前面的异步操作都执行完毕后,回到主线程.
for (int i = 0; i < 2; ++i) {
//模拟耗时操作
[NSThread sleepForTimeInterval:2];
//打印当前线程
NSLog(@"3---%@",[NSThread currentThread]);
}
NSLog(@"group---end");
});
NSLog(@"code end");
}
屏幕快照 2020-07-06 下午2.31.11.png
网友评论