一、延迟执行:dispatch_after
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
});
二、栅栏方法:dispatch_barrier_async 在执行完栅栏前面的操作之后,再执行栅栏操作,最后再执行栅栏后面的操作
dispatch_async(concurrent_queue, ^{
});
dispatch_barrier_async(concurrent_queue, ^{
});
dispatch_async(concurrent_queue, ^{
});
三、一次性代码:dispatch_once 程序运行过程中,只被执行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//只执行一次的代码 默认是线程安全的
});
四、快速迭代方法:dispatch_apply 按照指定的次数将指定的任务追加到指定的队列当中,等待队列的任务执行完成
dispatch_apply(6, concurrent_queue, ^(size_t index) {
NSLog(@"%zd---%@",index, [NSThread currentThread]);
});
NSArray *array = @[@"第一个",@"第二个",@"第三个",@"第四个",@"第五个",@"第六个"];
dispatch_apply(array.count, concurrent_queue, ^(size_t index) {
NSString *string = array[index];
NSLog(@"array当前的元素为:%@",string);
});
五、组队列:dispatch_group dispatch_group_notify dispatch_group_wait 两个异步执行的任务完成之后再回到主队列
//dispatch_group_notify
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
});
//dispatch_group_wait
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
});
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);//等待上面的任务完成后在继续执行下面的(会阻塞当前的线程)
//dispatch_group_enter dispatch_group_leave
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_group_leave(group);
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
});
dispatch_group_enter 标志着一个任务追加到group中执行一次,相当于group中未完成的任务+1 dispatch_group_leave 标志着一个任务离开了group,相当于group中未完成的任务-1 组合在一起相当于dispatch_group_asyn