iOS 多线程 --- NSOperation、NSOperationQueue

一. 概念

1. NSOperationNSOperationQueue是基于GCD的更高一层的封装。

2. 操作 NSOperation

  • NSOperation,执行的操作,对应于GCD的同异步中block里面的任务
  • 使用两个子类:NSInvocationOperationNSBlockOperation或者继承于NSOperation自定义子类来封装操作。

3. 操作队列 NSOperationQueue

  • NSOperationQueue,存放操作的队列。
  • NSOperationQueue里面任务的执行顺序通过设置优先级Priority和依赖关系Dependency进行控制。
  • 通过设置最大并发操作数maxConcurrentOperationCount来控制串行或者并发。
  • NSOperationQueue提供两种不同类型的队列:主队列(运行在主线程上)和自定义队列。

4. 使用说明

  • NSOperation单独使用时,是同步执行操作。需要配合NSOperationQueue实现多线程。
  • 第一步,创建操作:将需要执行的操作封装到一个NSOperation对象中。
  • 第二步,创建操作队列NSOperationQueue,然后将NSOperation对象放到NSOperationQueue里面。

二. NSOperation的使用

注:NSOperation是个抽象类,不能用来封装操作。使用它的两个子类NSInvocationOperationNSBlockOperation或者自定义子类来封装操作。

1. NSInvocationOperation

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"---");
    NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(LoadData) object:nil];
    [op start];
    NSLog(@"+++");
}
- (void)LoadData{
    [NSThread sleepForTimeInterval:2];
    NSLog(@"currentThread---%@",[NSThread currentThread]);
}
 ---
 currentThread---<NSThread: 0x6000008e6940>{number = 1, name = main}
 +++
  • 单独使用子类NSInvocationOperation进行操作的时候,不会开启新的线程。
  • 当前线程会阻塞,必须所有任务都执行完成之后,才能执行NSInvocationOperation后面的代码。

2. NSBlockOperation

NSLog(@"---");
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"currentThread---%@", [NSThread currentThread]);
}];
[op start];
NSLog(@"+++");
 ---
 currentThread---<NSThread: 0x600000ad0100>{number = 1, name = main}
 +++
  • 单独使用子类NSBlockOperation进行操作的时候(不添加额外操作),不会开启新的线程。
  • 当前线程会阻塞,必须所有任务都执行完成之后,才能执行NSBlockOperation后面的代码。

addExecutionBlock:在外部给NSBlockOperation添加操作。

NSLog(@"---");
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"currentThread---%@", [NSThread currentThread]);
}];
[op addExecutionBlock:^{
    [NSThread sleepForTimeInterval:1.0];
    NSLog(@"currentThread1---%@", [NSThread currentThread]);
}];
[op addExecutionBlock:^{
    [NSThread sleepForTimeInterval:1.0];
    NSLog(@"currentThread2---%@", [NSThread currentThread]);
}];
[op start];
NSLog(@"+++");
 ---
 currentThread2---<NSThread: 0x600000762d00>{number = 4, name = (null)}
 currentThread1---<NSThread: 0x600000755180>{number = 3, name = (null)}
 currentThread---<NSThread: 0x60000073d280>{number = 1, name = main}
 +++
  • 当前线程会阻塞,必须所有任务都执行完成之后,才能执行NSBlockOperation后面的代码。
  • 配合addExecutionBlock:使用,如果额外添加的操作足够多的话,会开启新的线程(由系统决定)。
  • 所有的操作(原先block里面的操作和通过addExecutionBlock:添加进去的额外操作)在不同的线程中异步执行。
  • 多试验几次,还会发现原先block里面的操作也有可能不在当前的线程中执行。

总结:

  • 单独使用NSBlockOperation进行操作的时候,一定会造成当前线程阻塞
  • 如果不添加额外操作,那么不会开启新的线程,block中的任务在当前线程执行。
  • 如果配合addExecutionBlock:添加额外操作,可能会开启新的线程。
  • 如果开启新的线程,操作会在不同的线程中异步执行,而且block中的操作有可能不在当前的线程执行。

3. 继承于NSOperation的自定义子类

#import <Foundation/Foundation.h>
@interface wxhOperation : NSOperation
@end

#import "wxhOperation.h"
@implementation wxhOperation
- (void)main{
    if (!self.isCancelled) {
        [NSThread sleepForTimeInterval:2];
        NSLog(@"currentThread---%@", [NSThread currentThread]);
    }
}
@end
#import "ViewController.h"
#import "wxhOperation.h"
@interface ViewController ()
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"---");
    wxhOperation *op = [[wxhOperation alloc] init];
    [op start];
    NSLog(@"+++");
}
 ---
 currentThread---<NSThread: 0x600000d99380>{number = 1, name = main}
 +++
  • 单独使用自定义继承子类wxhOperation进行操作的时,不会开启新的线程。
  • 当前线程会阻塞,必须所有任务都执行完成之后,才能执行wxhOperation后面的代码。

三. NSOperationQueue的使用

注:NSOperationQueue有两种队列,另一种是主队列,一种是自定义队列

1. 主队列

NSOperationQueue *queue = [NSOperationQueue mainQueue];
  • 添加到主队列中的操作,一般都会在主线程中执行。
  • 如果有使用addExecutionBlock:添加的额外操作,那么也有可能在其他线程执行。
  • 一般会在主队列中进行UI刷新的操作。

2. 自定义队列

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  • 添加到自定义队列中的操作,就会在子线程中执行。
  • 一般会在自定义队列中执行耗时操作。

四. NSOperation加入到NSOperationQueue中使用

注:NSOperationQueue队列添加操作NSOperation有两种方法分别是addOperationaddOperationWithBlock

1. addOperation

先创建操作,再把操作加到队列里面。

NSLog(@"---");
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(LoadData) object:nil];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"currentThread2---%@", [NSThread currentThread]);
}];
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
    [NSThread sleepForTimeInterval:1.0];
    NSLog(@"currentThread3---%@", [NSThread currentThread]);
}];
[queue addOperation:op1];
[queue addOperation:op2];
[queue addOperation:op3];
NSLog(@"+++");

- (void)LoadData{
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"currentThread1---%@",[NSThread currentThread]);
}
 ---
 +++
 currentThread3---<NSThread: 0x600003541600>{number = 3, name = (null)}
 currentThread1---<NSThread: 0x600003541940>{number = 5, name = (null)}
 currentThread2---<NSThread: 0x600003541840>{number = 4, name = (null)}
  • 当前线程不会出现阻塞现象。
  • 开启了新的线程,并且并发执行。

2. addOperationWithBlock

不需要创建操作,直接在block里面添加操作。

NSLog(@"---");
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"currentThread1---%@", [NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:3.0];
    NSLog(@"currentThread2---%@", [NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:1.0];
    NSLog(@"currentThread3---%@", [NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"currentThread4---%@", [NSThread currentThread]);
}];
NSLog(@"+++");
 ---
 +++
 currentThread3---<NSThread: 0x600001744680>{number = 3, name = (null)}
 currentThread4---<NSThread: 0x600001744ac0>{number = 5, name = (null)}
 currentThread1---<NSThread: 0x600001744a00>{number = 4, name = (null)}
 currentThread2---<NSThread: 0x600001748940>{number = 6, name = (null)}
  • 当前线程不会出现阻塞现象。
  • 开启了新的线程,并且并发执行。

五. NSOperationQueue控制串行和并发

注:NSOperationQueue通过设置maxConcurrentOperationCount(最大并发操作数)来控制队列的串行和并发。

  • 默认maxConcurrentOperationCount-1,表示不进行限制,可并发执行。

1. 设置成串行队列

NSLog(@"---");
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 1;
[queue addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"currentThread1---%@", [NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:3.0];
    NSLog(@"currentThread2---%@", [NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:1.0];
    NSLog(@"currentThread3---%@", [NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"currentThread4---%@", [NSThread currentThread]);
}];
NSLog(@"+++");
---
+++
currentThread1---<NSThread: 0x60000046f3c0>{number = 3, name = (null)}
currentThread2---<NSThread: 0x60000046b180>{number = 4, name = (null)}
currentThread3---<NSThread: 0x60000046f3c0>{number = 3, name = (null)}
currentThread4---<NSThread: 0x60000046b180>{number = 4, name = (null)}
  • 设置maxConcurrentOperationCount1,队列为串行队列。
  • 当前线程不会阻塞
  • 虽然开启新的线程,但是队列里面的操作是同步执行,执行完第一个之后,才能执行第二个。

2. 设置成并发队列

NSLog(@"---");
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 10;
[queue addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"currentThread1---%@", [NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:3.0];
    NSLog(@"currentThread2---%@", [NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:1.0];
    NSLog(@"currentThread3---%@", [NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"currentThread4---%@", [NSThread currentThread]);
}];
NSLog(@"+++");
---
+++
currentThread3---<NSThread: 0x60000341ce80>{number = 3, name = (null)}
currentThread4---<NSThread: 0x600003426180>{number = 4, name = (null)}
currentThread1---<NSThread: 0x60000341cec0>{number = 5, name = (null)}
currentThread2---<NSThread: 0x600003410000>{number = 6, name = (null)}
  • 设置maxConcurrentOperationCount大于1,队列为并发队列,并行执行。
  • 当前线程不会阻塞
  • 开启新的线程,队列里面的操作是并发执行,可以多个一起执行。

六. 设置依赖关系

NSLog(@"---");
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(LoadData) object:nil];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"currentThread2---%@", [NSThread currentThread]);
}];
[op2 addDependency:op1];
[queue addOperation:op1];
[queue addOperation:op2];
NSLog(@"+++");

- (void)LoadData{
    [NSThread sleepForTimeInterval:3.0];
    NSLog(@"currentThread1---%@",[NSThread currentThread]);
}
---
+++
currentThread1---<NSThread: 0x600001dfbe80>{number = 3, name = (null)}
currentThread2---<NSThread: 0x600001dfbb80>{number = 4, name = (null)}
  • 设置操作op2依赖于操作op1,那么只有当op1执行完毕之后,才能执行op2

七. 设置优先级

优先级的取值

typedef NS_ENUM(NSInteger, NSOperationQueuePriority) {
    NSOperationQueuePriorityVeryLow = -8L,
    NSOperationQueuePriorityLow = -4L,
    NSOperationQueuePriorityNormal = 0,
    NSOperationQueuePriorityHigh = 4,
    NSOperationQueuePriorityVeryHigh = 8
};
  • NSOperation优先级默认为NSOperationQueuePriorityNormal,通过NSOperationqueuePriority属性给操作设置优先级。优先级主要体现在操作之间的争夺资源上,系统会优先处理queuePriority比较高的操作。
  • 当操作NSOperation添加到队列NSOperationQueue中时,首先会进入准备就绪状态,如果没有依赖关系,queuePriority比较高的NSOperation会优先进入就绪状态,进入就绪状态的操作才可以被执行。
  • 操作的queuePriority比较高,则优先进入就绪状态,而非优先结束操作执行。

八. 线程之间的通信

先自定义队列中执行耗时操作,然后在主队列中刷新UI。

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperationWithBlock:^{
        // 模拟耗时操作
        [NSThread sleepForTimeInterval:1.0];
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            // 更新UI。
        }];
    }];

九. 线程安全

需求:有时候,我们会在多个地方同时对同一个接口进行调用,那如果每次调用过程会对下一次调用的结果有影响(有修改或者更变等操作),那么我们就必须保证该接口同一时间只能被一个地方调用,这就是线程安全

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic,strong)NSLock *lock;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.lock = [[NSLock alloc] init];
    for (int i = 0; i < 10; i ++) {
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [queue addOperationWithBlock:^{
            [self tiaoyongjiekou];
        }];
    }
}
- (void)tiaoyongjiekou{
    [self.lock lock];
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 模拟耗时操作
        [NSThread sleepForTimeInterval:1.0];
        [weakSelf.lock unlock];
    });
}
@end

使用线程锁NSLock确保线程安全:

  • 初始化一个线程锁lock,默认是解锁状态,当第一次调用tiaoyongjiekou时,进入方法内部执行并且使用[self.lock lock]加锁(第一次调用执行完毕之前,处于加锁状态)。
  • 当执行完耗时操作时,使用[weakSelf.lock unlock]把锁解开。
  • 如果当第一次调用还没执行完毕,第二次就调用该方法时,因为self.lock处于加锁状态,那么线程阻塞,只能原地等待。等第一次调用结束,执行完耗时操作之后,执行了[weakSelf.lock unlock](此时就处于解锁状态),那么第二次调用才能继续执行。

十. 常用方法和属性总结

1. NSOperation

  • - (void)cancel; 将操作标记为取消状态
    注:该操作执行完毕后,不再执行新的操作,不是立即取消该操作。
  • - (BOOL)isFinished; 判断操作是否已经结束。
  • - (BOOL)isCancelled; 判断操作是否已经标记为取消。
  • - (BOOL)isExecuting; 判断操作是否正在在运行。
  • - (BOOL)isReady; 判断操作是否处于准备就绪状态。
    注:这个值和操作的依赖关系相关。
  • - (void)setCompletionBlock:(void (^)(void))block; 当前操作执行完毕时执行completionBlock里面的代码。
  • - (void)addDependency:(NSOperation *)op; 添加依赖,使当前操作依赖于操作op的完成。
  • - (void)removeDependency:(NSOperation *)op; 移除依赖,取消当前操作对操作op的依赖。

2. NSOperationQueue

  • - (void)cancelAllOperations; 将队列标记为取消状态
    注:该队列执行完毕后,不再执行新的队列,不是立即取消该队列。
  • - (BOOL)isSuspended; 判断队列是否处于暂停状态。YES为暂停状态,NO为恢复状态。
  • - (void)setSuspended:(BOOL)b; 可设置队列的暂停和恢复,YES代表暂停队列,NO代表恢复队列。
  • - (void)waitUntilAllOperationsAreFinished; 阻塞当前线程,直到队列中的操作全部执行完毕。
  • - (void)addOperationWithBlock:(void (^)(void))block; 向队列中添加一个NSBlockOperation类型操作对象。
  • - (void)addOperations:(NSArray *)ops waitUntilFinished:(BOOL)wait; 向队列中添加操作数组,wait标志是否阻塞当前线程直到所有操作结束。
  • - (NSArray *)operations; 当前在队列中的操作数组(某个操作执行结束后会自动从这个数组清除)。
  • - (NSUInteger)operationCount; 当前队列中的操作数。
  • + (id)currentQueue; 获取当前队列如果当前线程不是在NSOperationQueue上运行则返回nil
  • + (id)mainQueue; 获取主队列。

注:暂停和取消的区别就在于

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

推荐阅读更多精彩内容