目的:执行完第一个任务再执行第二个任务
方法一:dispatch_barrier_async配合DISPATCH_QUEUE_CONCURRENT线程,先执行barrier前面的任务,再执行后面的任务。
- (void)barrier {
// 必须用DISPATCH_QUEUE_CONCURRENT,dispatch_barrier_async才有作用
dispatch_queue_t queue = dispatch_queue_create("concurrent", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"1-----%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"2-----%@",[NSThread currentThread]);
});
// 执行完barrier之前的任务才能执行barrier之后的任务
dispatch_barrier_async(queue, ^{
NSLog(@"barrier------%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"3-----%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"4-----%@",[NSThread currentThread]);
});
}
方法二:dispatch_group_enter和dispatch_group_leave
- (void)enterThenLeave {
// 创建线程组
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 1、2并行
dispatch_group_enter(group);// 添加任务开始标识
for (NSInteger i = 0; i < 2; i ++) {
NSLog(@"2-----%@",[NSThread currentThread]);
if (i == 1) {
dispatch_group_leave(group);// 添加任务结束标识
}
}
dispatch_group_enter(group);
for (NSInteger i = 0; i < 2; i ++) {
NSLog(@"1-----%@",[NSThread currentThread]);
if (i == 1) {
dispatch_group_leave(group);
}
}
});
// 所有任务都执行dispatch_group_leave后才执行这个方法
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"3------");
});
}
网友评论