多线程Operation

  • NSOperation的作用
    • 配合使用NSOperation和NSOperationQueue也能实现多线程编程
    • NSOperation和NSOperationQueue实现多线程的具体步骤
    • 先将需要执行的操作封装到一个NSOperation对象中
    • 然后将NSOperation对象添加到NSOperationQueue中
    • 系统会自动将NSOperationQueue中的NSOperation取出来
    • 将取出的NSOperation封装的操作放到一条新线程中执行
  • NSOperation的子类
    • NSInvocationOperation
    • NSBlockOperation
    • 自定义子类继承NSOperation,实现内部相应的方法

1. NSInvocationOperation

- (void)InvocationOperation{
     // 1.创建操作, 封装任务
      /*
       第一个参数: 目标对象, self
       第二个参数: 调用方法的名称
       第三个参数: 前面方法需要接收的参数 nil
       */
      NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run1) object:nil];
      NSInvocationOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run2) object:nil];
      NSInvocationOperation *op3 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run3) object:nil];
    // 2.创建队列
    /*
      GCD的队列类型:
        串行类型: create & 主队列
        并发类型: create & 全局并发队列
     
      NSOperation:
        主队列: [NSOperationQueue mainQueue]和GCD的主队列一样, 串行队列
        非主队列: [[NSOperationQueue alloc] init] 非常特殊(同时具备串行和并发的功能)
        默认情况下, 非主队列是并发队列
     */
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];
    

}   

- (void)run1{
    NSLog(@"%@", [NSThread currentThread]);
}

- (void)run2{
    NSLog(@"%@", [NSThread currentThread]);
}
- (void)run3{
    NSLog(@"%@", [NSThread currentThread]);
}

2. NSBlockOperation

- (void)blockOperation{
    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
    // 在主线程
    NSLog(@"__%@", [NSThread currentThread]);
 }];

// 添加额外的任务(在子线程中执行)
    [op addExecutionBlock:^{
        NSLog(@"下载2__%@", [NSThread currentThread]);
  }];

   [op addExecutionBlock:^{
    NSLog(@"下载3__%@", [NSThread currentThread]);
  }];

   [op addExecutionBlock:^{
    NSLog(@"下载4__%@", [NSThread currentThread]);
  }];

  [op start];
}

打印结果

<NSThread: 0x600000260ec0>{number = 5, name = (null)}
下载2__<NSThread: 0x60800007b900>{number = 1, name = main}
下载4__<NSThread: 0x60000007bf80>{number = 7, name = (null)}
下载3__<NSThread: 0x600000261600>{number = 6, name = (null)}

可以看出如果一个操作(一个NSBLockOperation对象)中的任务数量大于1, 那么会开子线程执行并发任务


NSOperation对象添加到NSOperationQueue

- (void)blockOperation{
 
 NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
     NSLog(@"op1---%@", [NSThread currentThread]);
 }];
 
 [op1 addExecutionBlock:^{
     NSLog(@"下载1__%@", [NSThread currentThread]);
 }];
 
 [op1 addExecutionBlock:^{
     NSLog(@"下载2__%@", [NSThread currentThread]);
 }];
 
 [op1 addExecutionBlock:^{
     NSLog(@"下载3__%@", [NSThread currentThread]);
 }];
 
 NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
     NSLog(@"op2---%@", [NSThread currentThread]);
 }];

 NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
     NSLog(@"op3---%@", [NSThread currentThread]);
 }];
 
 
 NSOperationQueue *queue = [[NSOperationQueue alloc] init];
 [queue addOperation:op1];
 [queue addOperation:op2];
 [queue addOperation:op3];

// 简便方法 1.创建操作 2.将操作添加到队列中
 [queue addOperationWithBlock:^{
     NSLog(@"addOperationWithBlock---%@", [NSThread currentThread]);
 }];

 
}
op2---<NSThread: 0x60800007ff00>{number = 4, name = (null)}
op1---<NSThread: 0x608000078080>{number = 3, name = (null)}
下载1__<NSThread: 0x608000272dc0>{number = 5, name = (null)}
addOperationWithBlock---<NSThread: 0x608000262e00>{number = 7, name = (null)}
op3---<NSThread: 0x600000279080>{number = 6, name = (null)}
下载2__<NSThread: 0x608000078080>{number = 3, name = (null)}
下载3__<NSThread: 0x60800007ff00>{number = 4, name = (null)}

打印结果显示也是并发执行的
如果使用blockOperationWithBlockNSInvocationOperation创建的操作中代码非常多, 可以使用自定义的子类继承NSOperation, 实现内部的main方法。
好处和其他的自定义控件一样有利于代码隐藏和提高代码复用性。

上面说到非主队列, 即[[NSOperationQueue alloc] init]创建的队列默认情况下是并发队列, 怎么让它变成串行队列呢:

- (void)maxConrurrentOperationCount{
 NSOperationQueue *queue = [[NSOperationQueue alloc] init];
 
 // 设置并发数量maxConcurrentOperationCount(同一时间最多有多少个任务在执行)
 // static const NSInteger NSOperationQueueDefaultMaxConcurrentOperationCount = -1;系统默认为-1, 特殊意义  最大值 表示不受限制

 queue.maxConcurrentOperationCount = 3;
 
 for (int i = 0; i < 10; i++) {
     NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
         NSLog(@"i=%d, %@", i,[NSThread currentThread]);
     }];
     [queue addOperation:operation];
 }
}

打印结果

 i=0, <NSThread: 0x60800007e180>{number = 5, name = (null)}
 i=1, <NSThread: 0x600000260c00>{number = 6, name = (null)}
 i=2, <NSThread: 0x600000278e00>{number = 7, name = (null)}
 i=3, <NSThread: 0x60800007e180>{number = 5, name = (null)}
 i=4, <NSThread: 0x600000260c00>{number = 6, name = (null)}
 i=5, <NSThread: 0x600000278e00>{number = 7, name = (null)}
 i=6, <NSThread: 0x60800007e180>{number = 5, name = (null)}
 i=7, <NSThread: 0x600000260c00>{number = 6, name = (null)}
 i=8, <NSThread: 0x600000278e00>{number = 7, name = (null)}
 i=9, <NSThread: 0x60800007e180>{number = 5, name = (null)}

可以看出只开了3条线程并发执行
如果设置maxConcurrentOperationCount = 5

 i=0, <NSThread: 0x60800006c300>{number = 3, name = (null)}
 i=1, <NSThread: 0x60000006eb40>{number = 5, name = (null)}
 i=2, <NSThread: 0x600000070800>{number = 6, name = (null)}
 i=3, <NSThread: 0x60000007e940>{number = 7, name = (null)}
 i=4, <NSThread: 0x608000262c40>{number = 8, name = (null)}
 i=5, <NSThread: 0x60800006c300>{number = 3, name = (null)}
 i=6, <NSThread: 0x60000006eb40>{number = 5, name = (null)}
 i=7, <NSThread: 0x600000070800>{number = 6, name = (null)}
 i=8, <NSThread: 0x60000007e940>{number = 7, name = (null)}
 i=9, <NSThread: 0x608000262c40>{number = 8, name = (null)}

可以看出只开了5条线程并发执行
ps 串行队列的特点是同一时间只有一个任务在执行, 所以只要把maxConcurrentOperationCount设置为1就可以了

 i=0, <NSThread: 0x60000007a680>{number = 3, name = (null)}
 i=1, <NSThread: 0x60000007a680>{number = 3, name = (null)}
 i=2, <NSThread: 0x60000007a680>{number = 3, name = (null)}
 i=3, <NSThread: 0x60000007a680>{number = 3, name = (null)}
 i=4, <NSThread: 0x6080002667c0>{number = 4, name = (null)}
 i=5, <NSThread: 0x6080002667c0>{number = 4, name = (null)}
 i=6, <NSThread: 0x6080002667c0>{number = 4, name = (null)}
 i=7, <NSThread: 0x6080002667c0>{number = 4, name = (null)}
 i=8, <NSThread: 0x6080002667c0>{number = 4, name = (null)}
 i=9, <NSThread: 0x6080002667c0>{number = 4, name = (null)}

当设置masConcurrentOperationCount = 1时, 开启了两条线程串行执行任务, 串行队列是按照FIFO顺序执行任务, 而不是只开启一条线程

队列的状态: 队列中的任务也是有状态的: 已经执行完毕的 | 正在执行 | 队列等待状态

  1. 暂停[queue setSuspended:YES], 可以恢复继续执行[queue setSuspended:NO], 不能暂停正在继续执行的任务
  2. 取消[queue cancelAllOperations];, 不可以恢复
如何取消自定义Operation
新建类继承NSOPeration
// 自定义Operation只要重写main方法就可以了
- (void)main{
    
    for (int i = 0; i < 1000; i ++) {
        NSLog(@"download1----%d-----%@", i , [NSThread currentThread]);
    }
    
    for (int i = 0; i < 1000; i ++) {
        NSLog(@"download2----%d-----%@", i , [NSThread currentThread]);
    }

    
    for (int i = 0; i < 1000; i ++) {
        NSLog(@"download3----%d-----%@", i , [NSThread currentThread]);
    }

}
@property (nonatomic, strong) NSOperationQueue *operationQueue;

- (void)viewDidLoad
{

    self.operationQueue = [[NSOperationQueue alloc] init];
    
    CustomOperation *operation = [[CustomOperation alloc] init];
    
    [self.operationQueue addOperation:operation];
    
}

- (IBAction)cancell:(id)sender {
    [self.operationQueue cancelAllOperations];
}

现在点击取消执行cancell方法并没有效果, 它会将三个for循环都打印完, 如果我想执行完download1任务后可以这么做:

- (void)main{
    
    for (int i = 0; i < 1000; i ++) {
        NSLog(@"download1----%d-----%@", i , [NSThread currentThread]);
    }
    if (self.isCancelled) return;
    
    
    for (int i = 0; i < 1000; i ++) {
        NSLog(@"download2----%d-----%@", i , [NSThread currentThread]);
    }
    if (self.isCancelled) return;
    
    
    for (int i = 0; i < 1000; i ++) {
        NSLog(@"download3----%d-----%@", i , [NSThread currentThread]);
    }
    if (self.isCancelled) return;

}

NSOperation操作依赖
用NSOperation和NSOperationQueue处理a, b, c三个线程, 要求执行完a, b后才能执行c, 改怎么做?
    // 创建队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
   // 创建3个操作  1个NSOperation对应一个线程   
    NSOperation *a = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"operation-----a");
    }];
    
    NSOperation *b = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"operation-----b");
    }];

    NSOperation *c = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"operation-----c");
    }];
    
    
    // 添加依赖
    [c addDependency:a];  // 只有当a操作执行完, 才会执行c操作
    [c addDependency:b];  // 只有当b操作执行完, 才会执行c操作
    
    // 执行操作    应该先添加依赖才添加到队列(addOperation)里面去, 因为一旦添加到队列就开始创建线程, 执行相关线程的方法
    [queue addOperation:a];
    [queue addOperation:b];
    [queue addOperation:c];

结果

operation-----b
operation-----a
operation-----c

不能相互依赖, 即 [c addDependency:a];[a addDependency:c];如果这样写, 也不会崩溃, 而是谁都不执行

也可以两个跨队列(NSOperationQueue)依赖

// 跨队列依赖
- (void)dependency1{
    // 创建队列
    NSOperationQueue *queueA = [[NSOperationQueue alloc] init];
    NSOperationQueue *queueB = [[NSOperationQueue alloc] init];
    
    // 创建3个操作  1个NSOperation对应一个线程
    NSOperation *a = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"operation-----a");
    }];
    
    NSOperation *b = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"operation-----b");
    }];
    
    NSOperation *c = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"operation-----c");
    }];
    
    
    // 添加依赖
    [c addDependency:a];  // 只有当a操作执行完, 才会执行c操作
    [c addDependency:b];  // 只有当b操作执行完, 才会执行c操作
    
    // 执行操作    应该先添加依赖才添加到队列(addOperation)里面去, 因为一旦添加到队列就开始创建线程, 执行相关线程的方法
    [queueA addOperation:a];
    [queueB addOperation:b];
    [queueB addOperation:c];
}

结果也是一样的

operation-----b
operation-----a
operation-----c
NSOperation监听

可能会有这样一种场景, 比如下载电影, 我希望在电影下载完以后通知一下用户, 这时候就需要NSOPeration监听

- (void)completion{
    // 创建队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    // 创建3个操作  1个NSOperation对应一个线程
    NSBlockOperation *a = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"operation-----a, %@", [NSThread currentThread]);
    }];
    
    NSBlockOperation *b = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"operation-----b, %@", [NSThread currentThread]);
    }];
    
    NSBlockOperation *c = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"operation-----c, %@", [NSThread currentThread]);
    }];
    
    c.completionBlock = ^{
        NSLog(@"c操作完成 %@", [NSThread currentThread]);
    };
    
    
    [queue addOperation:a];
    [queue addOperation:b];
    [queue addOperation:c];
}
 operation-----a, <NSThread: 0x608000264640>{number = 4, name = (null)}
 operation-----b, <NSThread: 0x6080000725c0>{number = 8, name = (null)}
 operation-----c, <NSThread: 0x60800007d6c0>{number = 3, name = (null)}
 c操作完成 <NSThread: 0x60800007d6c0>{number = 3, name = (null)}

NSOperation线程通讯

- (void)viewDidLoad
{
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
    
    NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
       
        NSURL *url = [NSURL URLWithString:@"https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=王者荣耀&step_word=&hs=0&pn=5&spn=0&di=64062655030&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=2202721532%2C3099894817&os=1973914981%2C428613933&simid=4092530312%2C469771017&adpicid=0&lpn=0&ln=1976&fr=&fmq=1489296515341_R&fm=rs6&ic=undefined&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=卡通图片&objurl=http%3A%2F%2Fwww.demaxiya.com%2Fmoba%2Fattachment%2F1511%2F2-15111Q1042R26.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3B1j4wxtyw_z%26e3Bv54AzdH3F45kwAzdH3Foz6yAzdH3Ftg1jx88_z%26e3Bip4s&gsm=0&rpstart=0&rpnum=0"];
        NSData *imageData = [NSData dataWithContentsOfURL:url];
        
        UIImage *image = [UIImage imageWithData:imageData];
        
        NSLog(@"download----%@", [NSThread currentThread]);
        
        // 更新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.imageView.image = image;
            NSLog(@"UI----%@", [NSThread currentThread]);
        }];
    }];
    
    [operationQueue addOperation:operation];
}
 download----<NSThread: 0x608000078440>{number = 5, name = (null)}
 UI----<NSThread: 0x60000006a100>{number = 1, name = main}

我们可以使用GCD队列组下载两种图片合成一张图片, Operation也能做到

- (void)viewDidLoad
{
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
    
    __block UIImage *image1;
    __block UIImage *image2;
    NSBlockOperation *operationA = [NSBlockOperation blockOperationWithBlock:^{
        
        NSURL *url = [NSURL URLWithString:@"http://pic.qiantucdn.com/58pic/26/04/03/83S58PIC2Ev.jpg!qtwebp226"];
        NSData *imageData = [NSData dataWithContentsOfURL:url];
        
        image1 = [UIImage imageWithData:imageData];
        
        NSLog(@"downloadA----%@", [NSThread currentThread]);
    }];
    
    NSBlockOperation *operationB = [NSBlockOperation blockOperationWithBlock:^{
        
        NSURL *url = [NSURL URLWithString:@"http://pic.qiantucdn.com/58pic/26/04/03/83S58PIC2Ev.jpg!qtwebp226"];
        NSData *imageData = [NSData dataWithContentsOfURL:url];
        
        image2 = [UIImage imageWithData:imageData];
        
        NSLog(@"downloadB----%@", [NSThread currentThread]);
    }];
    
    NSBlockOperation *combieOperation = [NSBlockOperation blockOperationWithBlock:^{
       
        UIGraphicsBeginImageContext(CGSizeMake(200, 200));
        
        [image1 drawInRect:CGRectMake(0, 0, 100, 200)];
        
        [image2 drawInRect:CGRectMake(100, 0, 100, 200)];
        
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            self.imageView.image = image;
            
            NSLog(@"UI----%@", [NSThread currentThread]);
        }];
        
        
    }];

    
    [combieOperation addDependency:operationA];
    [combieOperation addDependency:operationB];

    
    [operationQueue addOperation:operationA];
    [operationQueue addOperation:operationB];
    [operationQueue addOperation:combieOperation];

    
}

 downloadB----<NSThread: 0x60000007e680>{number = 3, name = (null)}
 downloadA----<NSThread: 0x600000268100>{number = 4, name = (null)}
 UI----<NSThread: 0x608000076880>{number = 1, name = main}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,222评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,455评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,720评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,568评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,696评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,879评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,028评论 3 409
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,773评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,220评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,550评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,697评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,360评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,002评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,782评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,010评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,433评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,587评论 2 350

推荐阅读更多精彩内容