官方文档
混淆的地方
最大线程数量&当maxConcurrentOperationCount = 1 queue为串行队列&控制NSBlockOperation的多少.
实践
一.maxConcurrentOperationCount = 1时
1.纯NSBlockOperation验证
NSBlockOperation *blockop1 = [NSBlockOperation blockOperationWithBlock:^{
for (NSInteger i=0; i<5;i++ ) {
[NSThread sleepForTimeInterval:2];
NSLog(@"block1---0操作 %@",[NSThread currentThread]);
}
}];
[blockop1 addExecutionBlock:^{
for (NSInteger i=0; i<4;i++ ) {
[NSThread sleepForTimeInterval:2];
NSLog(@"block1-----1操作 %@",[NSThread currentThread]);
}
}];
[blockop1 addExecutionBlock:^{
for (NSInteger i=0; i<3;i++ ) {
[NSThread sleepForTimeInterval:2];
NSLog(@"block1add-----2操作 %@",[NSThread currentThread]);
}
}];
NSBlockOperation *blockop2 = [NSBlockOperation blockOperationWithBlock:^{
for (NSInteger i=0; i<7;i++ ) {
[NSThread sleepForTimeInterval:2];
NSLog(@"block2----总操作 %@",[NSThread currentThread]);
}
}];
[blockop2 addExecutionBlock:^{
for (NSInteger i=0; i<6;i++ ) {
[NSThread sleepForTimeInterval:2];
NSLog(@"block2add-----1操作 %@",[NSThread currentThread]);
}
}];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
queue.maxConcurrentOperationCount = 1;
[queue addOperations:@[blockop1,blockop2] waitUntilFinished:NO];
打印
当queue中有2个任务操作时 queue.maxConcurrentOperationCount = 1会开启新的线程所以同一时间执行同一类型的任务操作
2.纯NSInvocationOperation验证
NSInvocationOperation *inoperation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test) object:nil];
NSInvocationOperation *inoperation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test) object:nil];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
queue.maxConcurrentOperationCount = 1;
[queue addOperations:@[inoperation,inoperation2] waitUntilFinished:NO];
打印
当queue中有2个任务操作时 queue.maxConcurrentOperationCount = 1同一时间执行同一类型的任务操作
3.NSInvocationOperation+NSBlockOperation验证
NSBlockOperation *blockop1 = [NSBlockOperation blockOperationWithBlock:^{
for (NSInteger i=0; i<5;i++ ) {
[NSThread sleepForTimeInterval:2];
NSLog(@"block1---0操作 %@",[NSThread currentThread]);
}
}];
[blockop1 addExecutionBlock:^{
for (NSInteger i=0; i<4;i++ ) {
[NSThread sleepForTimeInterval:2];
NSLog(@"block1-----1操作 %@",[NSThread currentThread]);
}
}];
[blockop1 addExecutionBlock:^{
for (NSInteger i=0; i<3;i++ ) {
[NSThread sleepForTimeInterval:2];
NSLog(@"block1add-----2操作 %@",[NSThread currentThread]);
}
}];
NSInvocationOperation *inoperation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test) object:nil];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
queue.maxConcurrentOperationCount = 1;
[queue addOperations:@[blockop1,inoperation] waitUntilFinished:NO];
打印:
当queue中有2个任务操作时 queue.maxConcurrentOperationCount = 1也会开启新的线程 同一时间片执行了同一类型的任务操作