- NSOperationQueue属性
NSOperationQueue *queue = [[NSOperationQueue alloc] init];//创建队列
// 设置最大并发操作数
queue.maxConcurrentOperationCount = -1;//-1默认值不作限制,0为没有队列,1为串行队列,>1为并行队列
[queue cancelAllOperations];//取消所有的操作,为每个操作发送cancel,取消后不可恢复
queue.suspended = NO;//设置是否暂停(挂起)队列
@interface YQOperation : NSOperation
@end
@implementation YQOperation
//需要执行的任务
-(void)main{
for (NSInteger i = 0; i<1000; i++) {
NSLog(@"download1 -%zd-- %@", i, [NSThread currentThread]);
}
//判断是否已经取消了操作
if (self.isCancelled) return;
for (NSInteger i = 0; i<1000; i++) {
NSLog(@"download2 -%zd-- %@", i, [NSThread currentThread]);
}
}
@end
@interface ViewController ()
@end
@implementation ViewController
-(void)queue{
//创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//创建操作(任务)
NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(running) object:nil];
//创建操作(任务)
//一个正在执行的操作调用cancel方法,会执行完操作,可以在操作内用isCancelled判断
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
//如果正在执行耗时操作时,操作被取消了(执行了cancel),本操作会执行完,可以用isCancelled检测....
//检测到操作被取消,直接返回
if (op2.isCancelled)return;
NSLog(@"op2 --- %@", [NSThread currentThread]);
}];
//为op2追加操作(任务)
[op2 addExecutionBlock:^{
NSLog(@"op2 ---Execution--- %@", [NSThread currentThread]);
}];
[queue addOperation:op1];
[queue addOperation:op2];
[queue addOperation:[YQOperation new]];
//创建操作(任务)
[queue addOperationWithBlock:^{
NSLog(@"op3 --- %@", [NSThread currentThread]);
}];
}
-(void)running{
NSLog(@"running");
}
@end
设置依赖
执行结果:
download4----<NSThread: 0x7ff633d084b0>{number = 5, name = (null)}
download1----<NSThread: 0x7ff633c0af20>{number = 3, name = (null)}
download5----<NSThread: 0x7ff633c07490>{number = 4, name = (null)}
download2----<NSThread: 0x7ff633d0abe0>{number = 2, name = (null)}
op5执行完毕---<NSThread: 0x7ff633c07490>{number = 4, name = (null)}
download3----<NSThread: 0x7ff633d0abe0>{number = 2, name = (null)}
-(void)queue{
NSOperationQueue *queue = [[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]);
}];
NSBlockOperation *op4 = [NSBlockOperation blockOperationWithBlock:^{
sleep(0.5);
NSLog(@"download4----%@", [NSThread currentThread]);
}];
NSBlockOperation *op5 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"download5----%@", [NSThread currentThread]);
}];
op5.completionBlock = ^{
NSLog(@"op5执行完毕---%@", [NSThread currentThread]);
};
// 设置依赖后op1,op2,op4执行完成后才会执行op3
[op3 addDependency:op1];
[op3 addDependency:op2];
[op3 addDependency:op4];
[queue addOperation:op1];
[queue addOperation:op2];
[queue addOperation:op3];
[queue addOperation:op4];
[queue addOperation:op5];
}