「这是我参与2022首次更文挑战的第4天,活动详情查看:2022首次更文挑战」。
NSOperation是OC中多线程技术的一种,是对GCD的OC包装.它包含队列(NSOperationQueue)和操作(NSOperation)两个基本要素.
NSInvocationOperation,NSBlockOperation
- NSInvocationOperation
先看看这两个。
//NSInvocationOperation 没用NSOperationQueue,在主线程调用执行
-(void)demo
{
NSLog(@"---begin");
NSInvocationOperation *operation=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test) object:nil];
[operation start];
NSLog(@"---end");
}
-(void)test
{
[NSThread sleepForTimeInterval:4];
for (int i=0; i<3; i++) {
NSLog(@"---%d---%@",i,[NSThread currentThread]);
}
}
编译结果如下:
- NSBlockOperation
NSLog(@"---begin");
NSBlockOperation *blockOp=[NSBlockOperation blockOperationWithBlock:^{
[NSThread sleepForTimeInterval:4];
for (int i=0; i<3; i++) {
NSLog(@"---%d---%@",i,[NSThread currentThread]);
}
}];
[blockOp start];
NSLog(@"---end");
编译结果如下:
从上面两个编译结果可以看出,没有使用NSOperationQueue时,要调用start开始执行,没有开启新的线程,所以---end需要等其执行完再打印。
NSBlockOperation还有一种使用方法addExecutionBlock:可以添加更多操作。
NSLog(@"---begin");
//主线程中执行
NSBlockOperation *blockOp=[NSBlockOperation blockOperationWithBlock:^{
for (int i=0; i<3; i++) {
NSLog(@"---%d---%@",i,[NSThread currentThread]);
}
}];
//主线程和其他线程中执行
[blockOp addExecutionBlock:^{
[NSThread sleepForTimeInterval:2];
for (int i=3; i<6; i++) {
NSLog(@"---%d---%@",i,[NSThread currentThread]);
}
}];
[blockOp addExecutionBlock:^{
[NSThread sleepForTimeInterval:3];
for (int i=6; i<9; i++) {
NSLog(@"---%d---%@",i,[NSThread currentThread]);
}
}];
[blockOp start];
NSLog(@"---end");
编译结果如下:
从我这里的结果来说blockOperationWithBlock里的任务是在主线程执行的,addExecutionBlock里的任务是在主线程和其他线程执行的。而且这里NSBlockOperation时阻塞了主线程的,NSBlockOperation的任务执行完之后才打印---end,NSOperation的start方法默认是同步执行任务.
NSOperationQueue
接下来就看看这个了。
- [queue addOperation:invOp]
-(void)demo3
{
NSLog(@"---begin");
//队列
NSOperationQueue *queue=[[NSOperationQueue alloc]init];
queue.maxConcurrentOperationCount=-1;//最大并发数 1即为串行 默认-1并行
//任务
NSInvocationOperation *invOp=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test) object:nil];
NSBlockOperation *blockOp=[NSBlockOperation blockOperationWithBlock:^{
[NSThread sleepForTimeInterval:2];
for (int i=3; i<6; i++) {
NSLog(@"---%d---%@",i,[NSThread currentThread]);
}
}];
[queue addOperation:invOp];
[queue addOperation:blockOp];
NSLog(@"---end");
}
-(void)test
{
[NSThread sleepForTimeInterval:2];
for (int i=0; i<3; i++) {
NSLog(@"---%d---%@",i,[NSThread currentThread]);
}
}
编译结果如下: