GCD:
使用Dispatch Group追加block到Global Group Queue,这些block如果全部执行完毕,就会执行Main Dispatch Queue中的结束处理的block。
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, ^{ /*加载图片1 / });
dispatch_group_async(group, queue, ^{ /加载图片2 / });
dispatch_group_async(group, queue, ^{ /加载图片3 */ });
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// 合并图片
});
需要注意的:dispatch_group_wait是同步的所以不能放在主线程执行。
补充: dispatch_group会等和它关联的所有的dispatch_queue_t上的任务都执行完毕才会发出同步信号(dispathc_group_notify的代码块block会被执行,group_wait会结束等待)。也就是说一个group可以关联多个任务队列;下面给出示例:
- (void)groupSync2
{
dispatch_queue_t dispatchQueue = dispatch_queue_create("ted.queue.next1", DISPATCH_QUEUE_CONCURRENT);
dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
dispatch_group_t dispatchGroup = dispatch_group_create();
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
sleep(5);
NSLog(@"任务一完成");
});
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
sleep(6);
NSLog(@"任务二完成");
});
dispatch_group_async(dispatchGroup, globalQueue, ^{
sleep(10);
NSLog(@"任务三完成");
});
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
NSLog(@"notify:任务都完成了");
});
}
NSOperation:
// 创建队列
NSOperationQueue *queue1 = [[NSOperationQueue alloc] init];
// 添加操作
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"download1----%@", [NSThread currentThread]);
}];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"download2----%@", [NSThread currentThread]);
}];
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"download3----%@", [NSThread currentThread]);
}];
// 设置依赖(保证op3在op1和op2都执行完之后再执行)
[op3 addDependency:op1];
[op3 addDependency:op2];
[op1 start];
[op2 start];
[op3 start];
网友评论