多线程NSOperation--NSOperationQueue 的使用(三)

22 篇文章 0 订阅

转自:http://www.jianshu.com/p/bee5f359fe31


1 简单使用 NSOperationQueue

上一篇文章中看到使用自定义NSOperation来实现多线程,写法有些复杂,但其实,使用NSOperationQueue来实现多线程非常简单

- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建3个 NSInvocationOperation 操作
    NSOperationQueue *opQueue = [NSOperationQueue new];
    for (NSUInteger i = 0; i < 3; i++) {
        // 可以传递一个 NSObject 给operation的操作方法
        NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Operation_%lu", i] forKey:@"key"];
        NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationSelector:) object:dict];
        [opQueue addOperation:op];
    }
}

// NSInvocationOperation 操作执行的方法
- (void)operationSelector:(NSDictionary *)dict
{
    // 接收传进来的dict
    NSLog(@"dictValue = %@", [dict valueForKey:@"key"]);
    sleep(10);  // 加个睡眠模仿耗时操作
    NSLog(@"currentThread = %@", [NSThread currentThread]);
    NSLog(@"mainThread    = %@", [NSThread mainThread]);
}

控制台输出结果为:

2016-02-25 16:58:18.282 test[57194:18487531] dictValue = Operation_0
2016-02-25 16:58:18.282 test[57194:18487530] dictValue = Operation_1
2016-02-25 16:58:18.282 test[57194:18487533] dictValue = Operation_2
2016-02-25 16:58:28.283 test[57194:18487530] currentThread = <NSThread: 0x7fbf40435bb0>{number = 2, name = (null)}
2016-02-25 16:58:28.284 test[57194:18487531] currentThread = <NSThread: 0x7fbf4050f2a0>{number = 3, name = (null)}
2016-02-25 16:58:28.284 test[57194:18487533] currentThread = <NSThread: 0x7fbf4290f560>{number = 4, name = (null)}
2016-02-25 16:58:28.284 test[57194:18487530] mainThread    = <NSThread: 0x7fbf405058c0>{number = 1, name = (null)}
2016-02-25 16:58:28.284 test[57194:18487531] mainThread    = <NSThread: 0x7fbf405058c0>{number = 1, name = (null)}
2016-02-25 16:58:28.284 test[57194:18487533] mainThread    = <NSThread: 0x7fbf405058c0>{number = 1, name = (null)}

可以看出来这三个操作是并发执行的,而且都不在主线程中执行。

2 NSOperationQueue 的其他属性

添加操作有3个方法:

// 直接添加一个 NSOperation 操作,并且加入并发队列,只要当前队列允许,就会立刻执行。
- (void)addOperation:(NSOperation *)op;
// 添加一组操作,如果 waitUntilFinished 为 NO,则必须在当前队列中的所有操作都执行完了,才会执行这组操作,否则立刻执行。
- (void)addOperations:(NSArray<NSOperation *> *)ops waitUntilFinished:(BOOL)wait NS_AVAILABLE(10_6, 4_0);
// 直接在这里写一个block,block中的操作加入并发队列,并且只要当前队列允许执行,就会立刻执行。
- (void)addOperationWithBlock:(void (^)(void))block NS_AVAILABLE(10_6, 4_0);

接下来看其他的属性

// 返回当前队列中的所有操作NSOperation
@property (readonly, copy) NSArray<__kindof NSOperation *> *operations;
// 返回当前队列中的操作数量,对应 operations.count
@property (readonly) NSUInteger operationCount NS_AVAILABLE(10_6, 4_0);
// 可读写的属性,当设备性能不足或根据需求要限制并行的操作数量时,可以设置这个值。
// 设置了这个值之后,队列中并发执行的操作数量不会大于这个值。超出这个值在排队中的操作会处于休眠状态。
// 默认值为 NSOperationQueueDefaultMaxConcurrentOperationCount = -1
@property NSInteger maxConcurrentOperationCount;
// 可以给队列指定一个名字用来做标识
@property (nullable, copy) NSString *name NS_AVAILABLE(10_6, 4_0);
// 给队列指定一个优先级,默认为 NSQualityOfServiceDefault = -1
@property NSQualityOfService qualityOfService NS_AVAILABLE(10_10, 8_0);
// ??? 这个不是太理解
@property (nullable, assign /* actually retain */) dispatch_queue_t underlyingQueue NS_AVAILABLE(10_10, 8_0);
// 取消队列中的所有操作。其实就是调用 operations 中每个操作的`cancel`方法才取消操作。
// 但是,在前面的文章中说过,调用`cancel`方法并不会终止操作,而是设置`cancelled`属性为 YES,
// 这就需要自己在操作中分节点去判断`cancelled`属性了,在适当的时机结束操作。
- (void)cancelAllOperations;
// 调用这个方法时,会判断 NSOperationQueue 中的操作是否全部执行完,如果没有,则调用者所在的线程会在调用处等待。
// 直到 NSOperationQueue 中的所有操作执行完成,当前线程才继续执行。如果 NSOperationQueue 为空,则该方法立刻返回。
- (void)waitUntilAllOperationsAreFinished;
// 取得调用者的当前线程中的 NSOperationQueue 操作队列
+ (nullable NSOperationQueue *)currentQueue NS_AVAILABLE(10_6, 4_0);
// 取得主线程中的 
+ (NSOperationQueue *)mainQueue NS_AVAILABLE(10_6, 4_0);
@property (getter=isSuspended) BOOL suspended;

这个值很有意思,从字面意思理解是暂停队列,但是怎么个暂停呢?从官方文档上看

**Discussion**
When the value of this property is NO, the queue actively starts operations that are in the queue and ready to execute. Setting this property to YES prevents the queue from starting any queued operations, but already executing operations continue to execute. You may continue to add operations to a queue that is suspended but those operations are not scheduled for execution until you change this property to NO.

Operations are removed from the queue only when they finish executing. However, in order to finish executing, an operation must first be started. Because a suspended queue does not start any new operations, it does not remove any operations (including cancelled operations) that are currently queued and not executing.

You may monitor changes to the value of this property using key-value observing. Configure an observer to monitor the suspended key path of the operation queue.

The default value of this property is NO.

大概翻译一下,如果这个值设置为 NO,那说明这个队列已经准备好了可以执行了。如果这个值设置为 YES,那么已经添加到队列中的操作还是可以执行了,而后面继续添加进队列中的操作才处于暂停状态,直到你再次将这个值设置为 NO 时,后面加入的操作才会继续执行。这个属性的默认值是 NO。

来看一下使用的方法例子:

- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建3个 NSInvocationOperation 操作
    _opQueue = [NSOperationQueue new];
    for (NSUInteger i = 0; i < 3; i++) {
        // 可以传递一个 NSObject 给operation的操作方法
        NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Operation_%lu", i] forKey:@"key"];
        NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationSelector:) object:dict];
        [_opQueue addOperation:op];
    }
    // 这里设置为 YES
    _opQueue.suspended = YES;
    // 然后再添加一个操作,序号为 9
    NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Operation_%d", 9] forKey:@"key"];
    NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationSelector:) object:dict];
    [_opQueue addOperation:op];
}
// NSInvocationOperation 操作执行的方法
- (void)operationSelector:(NSDictionary *)dict
{
    // 接收传进来的dict
    NSLog(@"dictValue = %@", [dict valueForKey:@"key"]);
    sleep(10);  // 加个睡眠模仿耗时操作
    NSLog(@"currentThread = %@", [NSThread currentThread]);
    NSLog(@"mainThread    = %@", [NSThread mainThread]);
    // 执行完其中一个操作之后把 suspended 改为 NO。
    _opQueue.suspended = NO;
}
2016-02-25 17:22:07.546 test[57547:18605364] dictValue = Operation_2
2016-02-25 17:22:07.546 test[57547:18605360] dictValue = Operation_0
2016-02-25 17:22:07.546 test[57547:18605361] dictValue = Operation_1
2016-02-25 17:22:10.547 test[57547:18605361] currentThread = <NSThread: 0x7ff598d07b00>{number = 3, name = (null)}
2016-02-25 17:22:10.547 test[57547:18605364] currentThread = <NSThread: 0x7ff59a9784f0>{number = 2, name = (null)}
2016-02-25 17:22:10.547 test[57547:18605360] currentThread = <NSThread: 0x7ff59aa05100>{number = 4, name = (null)}
2016-02-25 17:22:10.547 test[57547:18605364] mainThread    = <NSThread: 0x7ff598c08770>{number = 1, name = (null)}
2016-02-25 17:22:10.547 test[57547:18605360] mainThread    = <NSThread: 0x7ff598c08770>{number = 1, name = (null)}
2016-02-25 17:22:10.547 test[57547:18605361] mainThread    = <NSThread: 0x7ff598c08770>{number = 1, name = (null)}
2016-02-25 17:22:10.547 test[57547:18605513] dictValue = Operation_9
2016-02-25 17:22:13.620 test[57547:18605513] currentThread = <NSThread: 0x7ff598c08ce0>{number = 5, name = (null)}
2016-02-25 17:22:13.620 test[57547:18605513] mainThread    = <NSThread: 0x7ff598c08770>{number = 1, name = (null)}

可以看出来,操作9是在suspended改为 NO 之后才开始执行的。

最后:以上很多属性都支持 KVO ,可以通过监听某个值的变化来做不同的操作,这里就不赘述了。

3 总结

NSOperationQueue为我们提供了非常简便的使用多线程的方法,如果需要使用NSOperation,则更多建议使用NSOperationQueue而不是自定义NSOperation



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值