我们常用的GCD调度组方式
1 //GCD常用调度组写法 2 -(void)demo1{ 3 4 //创建调度组和队列 5 dispatch_group_t group = dispatch_group_create(); 6 dispatch_queue_t queue = dispatch_queue_create("ChangYong", DISPATCH_QUEUE_CONCURRENT); 7 8 //将任务添加到调度组 9 dispatch_group_async(group, queue, ^{ 10 NSLog(@"耗时操作_11111111"); 11 }); 12 dispatch_group_async(group, queue, ^{ 13 //模拟耗时操作 14 [NSThread sleepForTimeInterval:2]; 15 NSLog(@"耗时操作_22222222"); 16 }); 17 dispatch_group_async(group, queue, ^{ 18 NSLog(@"耗时操作_33333333"); 19 }); 20 21 //所有任务执行完毕后执行的任务 22 dispatch_group_notify(group, dispatch_get_main_queue(), ^{ 23 NSLog(@"所有任务执行完毕, 更新UI操作"); 24 }); 25 }
GCD调度组原理
1 //GCD调度组原理方法 2 -(void)demo2{ 3 4 //创建调度组和队列 5 dispatch_group_t group = dispatch_group_create(); 6 dispatch_queue_t queue = dispatch_queue_create("YuanLi", DISPATCH_QUEUE_CONCURRENT); 7 8 //任务1 9 dispatch_group_enter(group); 10 dispatch_async(queue, ^{ 11 NSLog(@"任务1"); 12 dispatch_group_leave(group); 13 }); 14 15 //任务2 16 dispatch_group_enter(group); 17 dispatch_async(queue, ^{ 18 [NSThread sleepForTimeInterval:2]; 19 NSLog(@"任务2"); 20 dispatch_group_leave(group); 21 }); 22 23 //任务3 24 dispatch_group_enter(group); 25 dispatch_async(queue, ^{ 26 NSLog(@"任务3"); 27 dispatch_group_leave(group); 28 }); 29 30 //任务全部执行完毕 31 dispatch_group_notify(group, dispatch_get_main_queue(), ^{ 32 33 NSLog(@"任务执行完毕, 刷新UI"); 34 }); 35 36 //等待上面代码执行完毕后在执行下面的代码, 参数2:等待超时时间 37 //dispatch_group_wait(group, DISPATCH_TIME_FOREVER); 38 39 NSLog(@"Hello"); 40 }