//NSOpertionQueue NSOperation
//Queue
//主队列 和 自定义队列
//主队列是运行在主线程当中,自定义队列运行在后台
//NSOperation 定义需要执行的操作(任务)
//定义需要的操作,然后把该操作添加到合适的队列中
//三个步骤
//1.创建队列对象
//2.创建操作对象
//3.把操作对象添加到队列之中,等待队列分配线程执行操作
//1.创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//设置最大并发操作数
//队列中最多有几个操作同时执行
queue.maxConcurrentOperationCount = 1;
//是否暂停执行队列中的线程
[queue setSuspended:YES];
//2.创建操作
//NSOperation 不能直接使用
//使用子类的对象 两种方式1、直接创建 2、使用block创建
NSOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(thread1:)
object:@"op1 "];
NSOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(thread2:)
object:@"op2 "];
/*
NSBlockOperation *op3 = [[NSBlockOperation alloc] init];
[op3 addExecutionBlock:^{
//具体要执行的操作
}];
*/
//3.把操作加入到队列中
[queue addOperation:op1];
[queue addOperation:op2];
//加入之后,如果有操作,那队列就会自动执行
//4.设置操作的优先级
[op1 setQueuePriority:NSOperationQueuePriorityLow];
[op2 setQueuePriority:NSOperationQueuePriorityVeryHigh];
//5.设置操作之间的依赖关系
[op2 addDependency:op1]; //op2的执行依赖于op1,保证op1肯定op2之前执行
//是否重新让队列执行
[queue setSuspended:NO];
//回到主线程打印输出
for (int i = 0; i < 50; i ++) {
NSLog(@"主线程 : %d", i);
}
}
- (void)thread1:(NSString *)name
{
//具体要执行的操作
for (int i = 0; i < 50; i ++) {
NSLog(@"多线程 %@: %d", name, i);
}
}
- (void)thread2:(NSString *)name
{
for (int i = 0; i < 50; i ++) {
NSLog(@"多线程 %@: %d", name, i);
}
}