1、使用 NSOperation和NSOperationQueue实现
NSOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"第一个");
}];
NSOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"第二个");
}];
NSOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"第三个");
}];
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
// 添加依赖
[operation3 addDependency:operation1];
[operation3 addDependency:operation2];
// 添加到队列
[operationQueue addOperation:operation1];
[operationQueue addOperation:operation2];
[operationQueue addOperation:operation3];
2、Dispatch Group实现
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
NSLog(@"block0");
});
dispatch_group_async(group, queue, ^{
NSLog(@"block1");
});
dispatch_group_async(group, queue, ^{
NSLog(@"block2");
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"done");
});
// dispatch_release(group);
3、dispatch_group_wait
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
NSLog(@"block0");
});
dispatch_group_async(group, queue, ^{
NSLog(@"block1");
});
dispatch_group_async(group, queue, ^{
NSLog(@"block2");
});
// DISPATCH_TIME_FOREVER:永久等待 dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC):为等待1秒的时间
long result = dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
if (result == 0) {
// 属于Dispatch Group的全部处理已经执行结束
NSLog(@"全部执行结束");
} else {
// 属于Dispatch Group的某一个处理还在执行中
NSLog(@"还有处理在执行中");
}