NSOperation以及多线程技术比较

本文导读:NSOperation做为苹果推荐的重要并发技术之一,在开发当中也较为经常使用。本文将详细介绍NSOperation两个子类以及NSOperationQueue的使用。而笔者前面的文章[iOS多线程基础][1]已经详细介绍了简单的多线程NSThread和基于C语言的功能强大的GCD,有须要的同窗能够去看一下。既然有三种多线程技术,那它们又有什么区别呢?使用场景怎样呢?笔者将在本文末尾为你们一一解答bash

NSOperation是苹果推荐使用的并发技术,它提供了一些用GCD不是很好实现的功能。NSOperation是基于GCD的面向对象的使用OC语言的封装。相比GCD,NSOperation的使用更加简单。NSOperation是一个抽象类,也就是说它并不能直接使用,而是应该使用它的子类。使用它的子类的方法有三种,使用苹果为咱们提供的两个子类 NSInvocationOperation,NSBlockOperation和自定义继承自NSOperation的子类。多线程

NSOperation的使用经常是配合NSOperationQueue来进行的。只要是使用NSOperation的子类建立的实例就能添加到NSOperationQueue操做队列之中,一旦添加到队列,操做就会自动异步执行(注意是异步)。若是没有添加到队列,而是使用start方法,则会在当前线程执行。并发

咱们知道,线程间的通讯主要是主线程与分线程之间进行的。主线程到分线程,NSOperation子类也有相应带参数的方法;而分线程到主线程,好比更新UI,它也有很方便的获取主队列(被添加到主队列的操做默认会在主线程执行)的方法:[NSOperationQueue mainQueue]。异步

##1、NSInvocationOperation ###1.单个NSInvocationOperation <1>直接建立一个NSInvocationOperation的对象,而后调用start方法会直接在主线程执行性能

//1.建立
  NSOperation *op = [[NSInvocationOperation alloc]initWithTarget:self 
selector:@selector(downloadImage:) object:@"Invocation"];
 //2.start方法,直接在当前线程执行
    [op start];

#pragma mark - 调用的耗时操做,后面调用的耗时操做都是这个
- (void)downloadImage:(id)obj{
  NSLog(@"%@-----%@",[NSThread currentThread],obj);
}

复制代码
输出 [1151:50868] <NSThread: 0x7fae624047b0>{number = 1, name = main}-----Invocation
复制代码

<2>添加到NSOperationQueue优化

//1.建立
  NSOperation *op = [[NSInvocationOperation alloc]initWithTarget:self 
selector:@selector(downloadImage:) object:@"Invocation"];
 //2.放到队列里面去
    NSOperationQueue *q = [[NSOperationQueue alloc]init];
  //只要把操做放到队列,会自动异步执行调度方法
    [q addOperation:op];
复制代码
输出:[1192:55469] <NSThread: 0x7fbe59e45c30>{number = 3, name = (null)}-----Invocation
复制代码

在number为3,name为空的子线程执行ui

2.多个NSInvocationOperationatom

//队列,GCD里面的并发队列使用最多,因此NSOperation技术直接把GCD里面的并发队列封装起来
  //NSOperationQueue本质就是GCD里面的并发队列
  //操做就是GCD里面异步执行的任务
  NSOperationQueue *q = [[NSOperationQueue alloc]init];
 
  //把多个操做放到队列里面
  for (int i = 0; i < 100; i++) {
    NSOperation *op = [[NSInvocationOperation alloc]initWithTarget:self 
         selector:@selector(downloadImage:) object:[NSString stringWithFormat:@"Invocation%d",i]];
    [q addOperation:op];
  }
复制代码
输出:
**[1222:58476] <NSThread: 0x7fdc14b0cd20>{number = 7, name = (null)}-----Invocation5
**[1222:58478] <NSThread: 0x7fdc1357e5f0>{number = 9, name = (null)}-----Invocation7
**[1222:58307] <NSThread: 0x7fdc14a06ad0>{number = 3, name = (null)}-----Invocation1
**[1222:58477] <NSThread: 0x7fdc134916e0>{number = 8, name = (null)}-----Invocation6
**[1222:58481] <NSThread: 0x7fdc1357e120>{number = 12, name = (null)}-----Invocation10
**[1222:58475] <NSThread: 0x7fdc14801710>{number = 6, name = (null)}-----Invocation4
**[1222:58480] <NSThread: 0x7fdc13415630>{number = 11, name = (null)}-----Invocation9
**[1222:58306] <NSThread: 0x7fdc13512e20>{number = 4, name = (null)}-----Invocation3
··· ···
复制代码

线程名与输出均没有规律,很明显就是并发队列。spa

##2、NSBlockOperation线程

NSBlockOperation的用法与NSInvocationOperation相同,只是建立的方式不一样,它不须要去调用方法,而是直接使用代码块,显得更方便。这也使得NSBlockOperation比NSInvocationOperation更加流行

//跟GCD中的并发队列同样
  NSOperationQueue *q = [[NSOperationQueue alloc]init];
  //跟GCD中的主队列同样
//  NSOperationQueue *q = [NSOperationQueue mainQueue];
  //把多个操做放到队列里面
  for (int i = 0; i < 100; i++) {
    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
      NSLog(@"%@------%d",[NSThread currentThread],i);
     
   }];
    //把Block操做放到队列
    [q addOperation:op];
  }
  NSLog(@"完成");
复制代码
并发队列输出结果:
**[1378:72440] <NSThread: 0x7f9cb2603460>{number = 6, name = (null)}------5**
**[1378:72442] <NSThread: 0x7f9cb48106a0>{number = 5, name = (null)}------7**
**[1378:72441] <NSThread: 0x7f9cb242b3e0>{number = 7, name = (null)}------6**
**[1378:72325] <NSThread: 0x7f9cb4851550>{number = 9, name = (null)}------2**
**[1378:72320] <NSThread: 0x7f9cb492be70>{number = 4, name = (null)}------3**
**[1378:72313] <NSThread: 0x7f9cb24077b0>{number = 2, name = (null)}------1**
**[1378:72276] 完成
**[1378:72444] <NSThread: 0x7f9cb481cc40>{number = 11, name = (null)}------9**
**[1378:72326] <NSThread: 0x7f9cb4923fe0>{number = 3, name = (null)}------0**
**[1378:72440] <NSThread: 0x7f9cb2603460>{number = 6, name = (null)}------12**
... ...
复制代码
主队列输出结果:
**[1417:76086] 完成
**[1417:76086] <NSThread: 0x7fa452e04360>{number = 1, name = main}------0**
**[1417:76086] <NSThread: 0x7fa452e04360>{number = 1, name = main}------1**
**[1417:76086] <NSThread: 0x7fa452e04360>{number = 1, name = main}------2**
**[1417:76086] <NSThread: 0x7fa452e04360>{number = 1, name = main}------3**
**[1417:76086] <NSThread: 0x7fa452e04360>{number = 1, name = main}------4**
**[1417:76086] <NSThread: 0x7fa452e04360>{number = 1, name = main}------5**
**[1417:76086] <NSThread: 0x7fa452e04360>{number = 1, name = main}------6**
**[1417:76086] <NSThread: 0x7fa452e04360>{number = 1, name = main}------7**
... ...
复制代码

事实上NSBlockOperation有更简单的使用方法

NSOperationQueue *q = [[NSOperationQueue alloc]init];
 
  for (int i = 0; i < 10; i++) {
   
    [q addOperationWithBlock:^{
      NSLog(@"%@------%d",[NSThread currentThread],i);
    }];
  }
复制代码

##3、线程间通讯

主线程到子线程传对象,前面的例子里面已经有了,再也不缀述。下面的例子就是回到主线程更新UI。

p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; c

NSOperationQueue *q = [[NSOperationQueue alloc]init];

  [q addOperationWithBlock:^{
    NSLog(@"耗时操做--%@",[NSThread currentThread]);
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
      NSLog(@"更新UI-----%@",[NSThread currentThread]);
    }];
  }];
复制代码

##4、NSOperationQueue的一些高级操做 NSOperationQueue支持的高级操做有:队列的挂起,队列的取消,添加操做的依赖关系和设置最大并发数

<1>最大并发数

@property (nonatomic,strong)NSOperationQueue *opQueue;

//重写getter方法实现懒加载
- (NSOperationQueue*)opQueue{
  if (_opQueue == nil) {
    _opQueue = [[NSOperationQueue alloc]init]; 
  }
  return _opQueue;
}


#pragma mark - 高级操做:最大并发数

  //设置最大的并发数量(并不是线程的数量)
  self.opQueue.maxConcurrentOperationCount = 2;
  //把多个操做放到队列里面
  for (int i = 0; i < 10; i++) {
    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
      [NSThread sleepForTimeInterval:3.0];
      NSLog(@"%@------%d",[NSThread currentThread],i);
     
    }];
    //把Block操做放到队列
    [self.opQueue addOperation:op];
  }

复制代码

<2>线程的挂起

#pragma mark - 高级操做:线程的挂起
//暂停继续(对队列的暂停和继续),挂起的是队列,不会影响已经在执行的操做
- (IBAction)pause:(UIButton *)sender {
  //判断操做的数量,当前队列里面是否是有操做?
  if (self.opQueue.operationCount == 0) {
    NSLog(@"当前队列没有操做");
    return;
  }
 
  self.opQueue.suspended = !self.opQueue.isSuspended;
  if (self.opQueue.suspended) {
    NSLog(@"暂停");
   
  }else{
    NSLog(@"继续");
  }
}
复制代码

<3>取消队列里的全部操做

#pragma mark - 高级操做:取消队列里的全部操做
- (IBAction)cancelAll:(UIButton *)sender {
  //只能取消全部队列的里面的操做,正在执行的没法取消
  //取消操做并不会影响队列的挂起状态
  [self.opQueue cancelAllOperations];
  NSLog(@"取消队列里全部的操做");
  //取消队列的挂起状态
  //(只要是取消了队列的操做,咱们就把队列处于不挂起状态,以便于后续的开始)
  self.opQueue.suspended = NO;
 
}
复制代码

<4>依赖关系

/*
  * 例子
  *
  * 1.下载一个小说压缩包
  *  2.解压缩,删除压缩包
  * 3.更新UI
  */
 
  NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"1.下载一个小说压缩包,%@",[NSThread currentThread]);
   
  }];
 
  NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"2.解压缩,删除压缩包,%@",[NSThread currentThread]);
   
  }];
 
  NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"3.更新UI,%@",[NSThread currentThread]);
   
  }];
 
  //指定任务之间的依赖关系 --依赖关系能够跨队列(能够再子线程下载,在主线程更新UI)
 
  [op2 addDependency:op1];
  [op3 addDependency:op2];
//  [op1 addDependency:op3];  必定不能出现循环依赖
 
  //waitUntilFinished  相似GCD中的调度组的通知
  //NO不等待,直接执行输出come here
  //YES等待任务执行完再执行输出come here
  [self.opQueue addOperations:@[op1,op2] waitUntilFinished:YES];
 
 
  //在主线程更新UI
  [[NSOperationQueue mainQueue] addOperation:op3];
  [op3 addDependency:op2];
  NSLog(@"come here");
复制代码

还有一个NSOperationQueuePriority,队列优先级的概念,由于用的极少,因此这里不作介绍,确实有须要的同窗能够本身百度或者查看Documentation and API Reference。

##5、三种多线程技术 <1>NSThread

  • 优势:NSThread 比其余两个轻量级,使用简单
  • 缺点:须要本身管理线程的生命周期、线程同步、加锁、睡眠以及唤醒等。线程同步对数据的加锁会有必定的系统开销

<2>GCD GCD 是iOS 4.0之后才出现的并发技术

  • 使用方式:将任务添加到队列(串行/并行(全局)),指定执行任务的方法,(同步(阻塞)/异步 )
  • 拿到主队列:dispatch_get_main_queu()
  • NSOperation没法作到的:1.一次性执行,2.延迟执行,3.调度组(op实现要复杂的多 )

<3>NSOperation NSOperation iOS2.0的时候就出现了(当时很差用,后来苹果对其进行改造)

  • 使用方式:将操做(异步执行)添加到队列(并发/全局)
  • 拿到主队列:[NSOperationQueue mainQueue] 主队列,任务添加到主队列就会在主线程执行
  • 提供了GCD很差实现的:1.最大并发数,2.暂停和继续,3.取消全部任务,4.依赖关系

GCD是比较底层的封装,咱们知道较低层的代码通常性能都是比较高的,相对于NSOperationQueue。因此追求性能,而功可以用的话就能够考虑使用GCD。若是异步操做的过程须要更多的用户交互和被UI显示出来,NSOperationQueue会是一个好选择。若是任务之间没有什么依赖关系,而是须要更高的并发能力,GCD则更有优点。 高德纳的教诲:“在大概97%的时间里,咱们应该忘记微小的性能提高。过早优化是万恶之源。”只有Instruments显示有真正的性能提高时才有必要用低级的GCD。 [1]:http://www.jianshu.com/p/7267206834fb

相关文章
相关标签/搜索