NSOperation的串行、并行及自定义NSOperation的使用

这篇博客介绍了NSBlockOperation的使用,包括直接调用start进行同步执行以及通过NSOperationQueue实现异步并发。同时,详细讲解了自定义NSOperation的实现,包括重写start方法、executing和finished属性,以及如何通过KVO进行状态通知。文中还探讨了NSOperationQueue中maxConcurrentOperationCount对执行顺序的影响,以及如何在完成时触发completionBlock。最后,讨论了NSOperation的取消机制及其对后续执行的影响。
摘要由CSDN通过智能技术生成

1. NSBlockOperation

使用start

  • 使用start直接调用是同步的,在当前线程执行
#import <Foundation/Foundation.h>

int main(){
   
    //Demo1: start
    NSLog(@"当前线程是%@",[NSThread currentThread]);
    NSBlockOperation *blockOperation1 = [NSBlockOperation blockOperationWithBlock:^{
   
        NSLog(@"这是blockOperation1,线程%@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:3];
    }];
    
    NSBlockOperation *blockOperation2 = [NSBlockOperation blockOperationWithBlock:^{
   
        NSLog(@"这是blockOperation2,线程%@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:3];
    }];
    
    NSBlockOperation *blockOperation3 = [NSBlockOperation blockOperationWithBlock:^{
   
        NSLog(@"这是blockOperation3,线程%@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:3];
    }];
    [blockOperation1 start];
    [blockOperation2 start];
    [blockOperation3 start];
}

在这里插入图片描述

  • 向NSBlockOperation中添加ExecutionBlock,是异步的,会开启子线程,可能存在线程复用的情况
  • 几个operation之间是同步的,operation和它的几个executionBlock是异步的
#import <Foundation/Foundation.h>

int main(){
   
    //Demo1: start
    NSLog(@"当前线程是%@",[NSThread currentThread]);
    NSBlockOperation *blockOperation1 = [NSBlockOperation blockOperationWithBlock:^{
   
        NSLog(@"这是blockOperation1,线程%@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:3];
    }];
    [blockOperation1 addExecutionBlock:^{
   
        NSLog(@"这是blockOperation1的附加操作,线程%@",[NSThread currentThread]);
    }];


    NSBlockOperation *blockOperation2 = [NSBlockOperation blockOperationWithBlock:^{
   
        NSLog(@"这是blockOperation2,线程%@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:3];
    }];
    [blockOperation2 addExecutionBlock:^{
   
        NSLog(@"这是blockOperation2的附加操作,线程%@",[NSThread currentThread]);
    }];
    [blockOperation2 addExecutionBlock:^{
   
        NSLog(@"这是blockOperation2的附加操作2,线程%@",[NSThread currentThread]);
    }];
    
    [blockOperation1 start
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值