//创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
//封装操作
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"1-----------%@",[NSThread currentThread]);
}];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"2-----------%@",[NSThread currentThread]);
}];
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"3-----------%@",[NSThread currentThread]);
}];
NSBlockOperation *op4 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"4-----------%@",[NSThread currentThread]);
}];
op3.completionBlock = ^{//添加监听,操作执行完毕后 回调
NSLog(@"op3执行完毕。。");
};
//添加操作依赖 4->3->2->1 // 添加操作依赖能控制多任务并发的执行顺序,不能设置循环依赖,可以跨队列添加依赖
[op3 addDependency:op4];
[op2 addDependency:op3];
[op1 addDependency:op2];
//添加到队列中
[queue addOperation:op1];
[queue addOperation:op2];
[queue addOperation:op3];
[queue addOperation:op4];
执行结果:
2019-02-22 23:59:43.749883+0800 下载图片[15917:488100] 4-----------<NSThread: 0x600000e28100>{number = 3, name = (null)}
2019-02-22 23:59:43.750367+0800 下载图片[15917:488101] 3-----------<NSThread: 0x600000e34000>{number = 4, name = (null)}
2019-02-22 23:59:43.750513+0800 下载图片[15917:488100] 2-----------<NSThread: 0x600000e28100>{number = 3, name = (null)}
2019-02-22 23:59:43.750654+0800 下载图片[15917:488100] 1-----------<NSThread: 0x600000e28100>{number = 3, name = (null)}