定义一个全局的队列
@property (nonatomic,strong)NSOperationQueue *opQueue;
初始化对象
-(NSOperationQueue *)opQueue{
if (_opQueue ==nil) {
_opQueue = [[NSOperationQueuealloc]init];
}
return_opQueue;
}
设置最大并发数:不是线程的数量,而是同时执行操作的数量
self.opQueue.maxConcurrentOperationCount = 2;
for (int i =0; i < 20 ; i++) {
NSOperation *bp = [NSBlockOperationblockOperationWithBlock:^{
[NSThreadsleepForTimeInterval:1];
NSLog(@"%@ %d",[NSThreadcurrentThread],i);
}];
[self.opQueue addOperation:bp];
}
挂起:暂停和继续
self.opQueue.suspended
取消队列里的所有操作,取消操作并不会影响队列的挂起状态
[self.opQueue cancelAllOperations];
//取消队列里的挂起状态
self.opQueue.suspended =NO;
一:相当于GCD的并发(全局)队列
//主队列:与GCD主队列一致
NSOperationQueue *opq =[NSOperationQueuemainQueue];
//创建多个操作:相当于GCD的异步执行的任务
for (int i =0; i < 20 ; i++) {
NSOperation *op = [NSBlockOperationblockOperationWithBlock:^{
NSLog(@"%@ %d",[NSThreadcurrentThread],i);
}];
[opq addOperation:op];
}
二:依赖队列
NSOperationQueue *opq = [[NSOperationQueuealloc]init];
//常用写法
for (int i =0; i < 20 ; i++) {
[opq addOperationWithBlock:^{
NSLog(@"%@ %d",[NSThreadcurrentThread],i);
}];
}
//NSBlockOperation
NSBlockOperation *op1 = [NSBlockOperationblockOperationWithBlock:^{
NSLog(@"op1 %@",[NSThreadcurrentThread]);}];
[op1 addExecutionBlock:^{
NSLog(@"op1-11111");
}];
//NSInvocationOperation 不常用
NSOperation *op2 = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(task:)object:@"Invocation"]; //多态的写法
//依赖关系,可以跨队列,注意不要出现循环依赖
[op2 addDependency:op1];
//设置等待
[opq addOperations:@[op1,op2]waitUntilFinished:YES];
NSLog(@"等待执行");
//线程间通信:在主线程里更新UI
NSBlockOperation *op3 = [NSBlockOperationblockOperationWithBlock:^{
NSLog(@"更新UI......%@",[NSThreadcurrentThread]);}];
[[NSOperationQueuemainQueue] addOperation:op3];
[op3 addDependency:op2]; //依赖关系,可以跨队列