NSOperationQueue
NSOperationQueue
队列 包含了 主队列 和 非主队列
//创建主队列
NSOperationQueue * mainQueue = [NSOperationQueue mainQueue];
//创建非主队列
NSOperationQueue * otherQueue = [[NSOperationQueue alloc] init];
NSBlockOperation * opOne = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"线程 ------%@",[NSThread currentThread]);
NSLog(@"一号开始执行");
}];
[opOne addExecutionBlock:^{
NSLog(@"线程1 ------%@",[NSThread currentThread]);
NSLog(@"二号开始执行");
}];
[opOne addExecutionBlock:^{
NSLog(@"线程3 ------%@",[NSThread currentThread]);
NSLog(@"三号开始执行");
}];
//创建非主队列
NSOperationQueue * otherQueue = [[NSOperationQueue alloc] init];
[otherQueue addOperation:opOne];
线程1 ------<NSThread: 0x600000318fc0>{number = 4, name = (null)}
线程 ------<NSThread: 0x60000032f2c0>{number = 3, name = (null)}
线程3 ------<NSThread: 0x60000032f240>{number = 5, name = (null)}
三号开始执行
二号开始执行
一号开始执行
可以看出任务开始并发执行
任务依赖
NSInvocationOperation * op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocation) object:nil];
NSBlockOperation * opOne = [NSBlockOperation blockOperationWithBlock:^{
sleep(5);
NSLog(@"1结束了");
}];
NSBlockOperation * opTwo = [NSBlockOperation blockOperationWithBlock:^{
sleep(5);
NSLog(@"2结束了");
}];
NSOperationQueue * otherQueue = [[NSOperationQueue alloc] init];
otherQueue.maxConcurrentOperationCount = 1; //设置1 串行执行 大于1 并发执行 默认-1 不限制
op.queuePriority = NSOperationQueuePriorityVeryHigh;
[op addDependency:opOne];
[opTwo addDependency:op];
[otherQueue addOperation:opOne];
[otherQueue addOperation:op];
[otherQueue addOperation: opTwo];
-(void)invocation {
NSLog(@"线程4 ------%@",[NSThread currentThread]);
NSLog(@"任务结束了");
}
1结束了
线程4 ------<NSThread: 0x60000299b0c0>{number = 3, name = (null)}
任务结束了
2结束了