iOS ------多线程NSOperation,NSOperationQueue

1,NSOperation,NSOperationQueue简介

NSOperation,NSOperationQueue是苹果提供我们的一套多线程解决方案。实际上NSOperationa,NSOperationQueue是基于GCD更高一层的封装。但是比GCD更简单易用,代码可读性也会更高。

为什么要使用NSOperation,NSOperationQueue

  1. 可添加完成的代码块,在操作完成后执行
  2. 添加操作之间的依赖关系,方便控制执行顺序
  3. 设置操作执行的优先级
  4. 可以很方便的取消一个操作的执行
  5. 使用KVO观察对操作执行状态的更改:isExecuting(正在执行),isFinnished,isCancelled.

2,NSOperation,NSOperationQueue操作和操作队列

先对于GCD,NSOperation,NSOperationQueue中也有一些类似的概念:任务(操作)和队列(操作队列)。

1,操作(Operation):

  • 执行操作的意思,就是你要在线程中执行的那段代码
  • 在GCD中是放在block中的。在NSOperation,我们使用NSOperation子类NSInvocationOperationNSBlockOperation,或者自定义子类来封装操作

1,操作队列(Operation Queues)

  • 这里的队列指操作队列,即用来存放操作的队列。不同于GCD中调度队列FIFO(先进先出)的原则。NSOperationQueue对于添加到队列中的操作,首先进入准备就绪的状态(就绪状态取决于操作之间的依赖关系),然后进入就绪状态的操作的开始执行顺序(非结束执行顺序)由操作之间的相对的优先级决定(优先级是操作对象自身的属性)
  • 操作队列通过设置最大并发操作数来控制并发,串行
  • NSOperationQueue为我们提供了两种不同类型的队列:主队列和自定义队列。主队列运行在主线程,而自定义队列在后台执行

3,NSOperation,NSOperationQueue使用步骤

NSOperation实现多线程的使用步骤分为三步:

  1. 创建操作:先将需要执行的操作封装到一个NSOperation对象中
  2. 创建队列:创建NSOperationQueue对象
  3. 将操作加入到队列中:将 NSOperation 对象添加到 NSOperationQueue 对象中。

之后,系统就会自动将NSOperationQueue中的NSOperation取出来,在新线程中执行

4,NSOperation,NSOperationQueue基本使用

NSOperation是一个抽象类,不能用来封装操作,我们只能使用它的子类来封装操作。有三种方式:

  1. 使用子类 NSInvocationOperation
  2. 使用子类 NSBlockOperation
  3. 自定义继承自 NSOperation 的子类,通过实现内部相应的方法来封装操作。

在不使用 NSOperationQueue,单独使用 NSOperation 的情况下系统同步执行操作

4.1使用子类NSinvocationOperation

NSInvocationOperation提供了两种创建操作对象的方式:

  • initwithTarget:selector:object:
  • initWithInvocation:

创建完成后,均需要调用start方法,启动操作对象执行任务

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建NSInvocationOperation对象
    NSInvocationOperation* op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task) object:nil];
    //调用start方法开始执行操作
    [op start];
    // Do any additional setup after loading the view.
}
- (void)task {
    NSLog(@"---%@", [NSThread currentThread]);//打印当前线程
}

@end

运行结果

2024-05-20 21:56:48.058232+0800 NSOperation[73255:3995804] ---<_NSMainThread: 0x6000025fc000>{number = 1, name = main}

可以看出:在没有使用NSOperationQueue,在主线程单独使用子类 NSInvocationOperation 执行一个操作的情况下,操作是在当前线程执行的,并没有开启新线程,如果在其他线程中执行操作,则打印结果为其他线程。所以,在某个线程单独使用子类 NSInvocationOperation 执行一个操作的情况下,该操作就在某个线程执行

4.2,使用子类NSBlockOperation

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSBlockOperation * op = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"---%@", [NSThread currentThread]);
    }];
    [op start];
}
@end

运行结果

2024-05-20 22:14:43.849078+0800 NSOperation[73573:4009675] ---<_NSMainThread: 0x600001820040>{number = 1, name = main}

可以看到:在没有使用 NSOperationQueue、在主线程中单独使用 NSBlockOperation 执行一个操作的情况下,操作是在当前线程执行的,并没有开启新线程。和上边 NSInvocationOperation 使用一样。因为代码是在主线程中调用的,所以打印结果为主线程。如果在其他线程中执行操作,则打印结果为其他线程。

此外,NSBlockOperation还提供了一种方法addExecutionBlock:,通过addExecutionBlock:就可以为NSBlockOperation添加额外的操作。这些操作(包括blockOperationWithBlock中的操作)可以在不同的线程中同时(并发)执行。只有当所有相关操作已经完成§执行后,才视为完成

如果添加的操作多的话,blockOperationWithBlock:中的操作也可能会在其他线程(非当前线程)中执行,这时由系统决定的。

NSBlockOperation * op = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"1---%@", [NSThread currentThread]);
    }];
    [op addExecutionBlock:^{
        NSLog(@"2---%@", [NSThread currentThread]);
    }];
    [op addExecutionBlock:^{
        NSLog(@"3---%@", [NSThread currentThread]);
    }];
    [op addExecutionBlock:^{
        NSLog(@"4---%@", [NSThread currentThread]);
    }];
    [op addExecutionBlock:^{
        NSLog(@"5---%@", [NSThread currentThread]);
    }];
    [op addExecutionBlock:^{
        NSLog(@"6---%@", [NSThread currentThread]);
    }];
    [op addExecutionBlock:^{
        NSLog(@"7---%@", [NSThread currentThread]);
    }];
    [op addExecutionBlock:^{
        NSLog(@"8---%@", [NSThread currentThread]);
    }];
    [op addExecutionBlock:^{
        NSLog(@"9---%@", [NSThread currentThread]);
    }];
    [op start];

运行结果:

2024-05-21 20:15:14.816757+0800 NSOperation[1530:27171] 1---<NSThread: 0x600001c1dac0>{number = 6, name = (null)}
2024-05-21 20:15:14.816758+0800 NSOperation[1530:27044] 4---<_NSMainThread: 0x600001c44040>{number = 1, name = main}
2024-05-21 20:15:14.816754+0800 NSOperation[1530:27176] 2---<NSThread: 0x600001c02e40>{number = 4, name = (null)}
2024-05-21 20:15:14.816781+0800 NSOperation[1530:27173] 6---<NSThread: 0x600001c0c880>{number = 7, name = (null)}
2024-05-21 20:15:14.816780+0800 NSOperation[1530:27177] 7---<NSThread: 0x600001c10000>{number = 8, name = (null)}
2024-05-21 20:15:14.816782+0800 NSOperation[1530:27178] 8---<NSThread: 0x600001c03280>{number = 9, name = (null)}
2024-05-21 20:15:14.816756+0800 NSOperation[1530:27172] 3---<NSThread: 0x600001c050c0>{number = 5, name = (null)}
2024-05-21 20:15:14.816827+0800 NSOperation[1530:27171] 9---<NSThread: 0x600001c1dac0>{number = 6, name = (null)}
2024-05-21 20:15:14.816833+0800 NSOperation[1530:27175] 5---<NSThread: 0x600001c4e340>{number = 3, name = (null)}

可以看出:使用子类 NSBlockOperation,并调用方法 AddExecutionBlock: 的情况下,blockOperationWithBlock:方法中的操作 和 addExecutionBlock: 中的操作是在不同的线程中异步执行的。而且,这次执行结果中 blockOperationWithBlock:方法中的操作也不是在当前线程(主线程)中执行的。从而印证了 blockOperationWithBlock: 中的操作也可能会在其他线程(非当前线程)中执行。

一般情况。如果一个NSBlockOperation对象封装了多个操作。NSBlockOperation是否开启新线程,取决于操作的个数,当然开启线程的数量由系统来决定。

4.3使用自定义继承自NSOperation的子类

如果前面的两种方法不能满足日常的需求,我们可以使用自定义继自NSOperation的子类。可以通过重写main和start方法来自定义自己的NSOperation对象。重写main方法比较简单,我们不需要管理操作的状态属性isExecuting和isFinished。当main函数执行完饭回的时候,这个操作就结束了。

@interface ZDYNSOperation : NSOperation

@end
#import "ZDYNSOperation.h"

@implementation ZDYNSOperation
- (void)main {
    if (self.isCancelled) {
        for (int i = 0; i < 4; i++) {
            [NSThread sleepForTimeInterval:2];
            NSLog(@"%d ----- %@", i, [NSThread currentThread]);
        }
    }
}
@end

使用的时候导入头文件ZDYNSOperation.h

 ZDYNSOperation* ZDYop = [[ZDYNSOperation alloc] init];
    [ZDYop start];
2024-05-21 20:51:17.539261+0800 NSOperation[2261:56676] 0 ----- <_NSMainThread: 0x600002974640>{number = 1, name = main}
2024-05-21 20:51:19.540766+0800 NSOperation[2261:56676] 1 ----- <_NSMainThread: 0x600002974640>{number = 1, name = main}
2024-05-21 20:51:21.542204+0800 NSOperation[2261:56676] 2 ----- <_NSMainThread: 0x600002974640>{number = 1, name = main}
2024-05-21 20:51:23.543442+0800 NSOperation[2261:56676] 3 ----- <_NSMainThread: 0x600002974640>{number = 1, name = main}

可以看出:
在没有使用NSOperationQueue、在主线程单独使用自定义继承自 NSOperation 的子类的情况下,是在主线程执行操作,并没有开启新线程。

4.4创建队列

NSOperationQueue一共有两个队列:主队列,自定义队列。其中自定义队列同时包含了串行并发功能。

1,主队列

  • 凡是添加到队列中的操作,都会放在主线程中执行
// 主队列获取方法
NSOperationQueue *queue = [NSOperationQueue mainQueue];

2,自定义队列

  • 添加到这种队列中的操作,就会自动放在子线程中执行。
  • 同时包含了:串行,并发功能。
// 自定义队列创建方法
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

4.5将操作加入到队列中

NSOperation 需要配合 NSOperationQueue 来实现多线程。那么我们需要将创建好的操作加入到队列中去。总共有两种方法

1,- (void)addOperation:(NSOperation *)op;需要先创建好操作,在将创建好的操作加入到创建好的队列中

//创建队列
    NSOperationQueue* queue  = [[NSOperationQueue alloc] init];
    
    //创建操作
    NSInvocationOperation* op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task1) object:nil];
    NSInvocationOperation* op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task2) object:nil];
    
    NSBlockOperation* op3 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"3-----%@", [NSThread currentThread]);
    }];
    
    [op3 addExecutionBlock:^{
        NSLog(@"4-----%@", [NSThread currentThread]);
    }];
    //添加所有操作到队列,这里不用调用操作的start
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];

- (void)task1 {
    NSLog(@"1---%@", [NSThread currentThread]);//打印当前线程
}
- (void)task2 {
    NSLog(@"2---%@", [NSThread currentThread]);//打印当前线程
}

输出结果

2024-05-21 21:42:45.882962+0800 NSOperation[3223:94379] 1---<NSThread: 0x600000389700>{number = 7, name = (null)}
2024-05-21 21:42:45.882995+0800 NSOperation[3223:94381] 4-----<NSThread: 0x6000003dfc00>{number = 8, name = (null)}
2024-05-21 21:42:45.882996+0800 NSOperation[3223:94380] 3-----<NSThread: 0x6000003d9600>{number = 5, name = (null)}
2024-05-21 21:42:45.882996+0800 NSOperation[3223:94386] 2---<NSThread: 0x600000396500>{number = 6, name = (null)}

可以看出:
使用NSOperation子类创建操作,并使用addOperation:将操作加入到操作队列后能够开启新线程,进行并行执行。

2,- (void)addOperationWithBlock:(void (^)(void))block;无需先创建操作,在block中添加操作,直接将包含操作的block加入到队列中。

NSOperationQueue* queue  = [[NSOperationQueue alloc] init];
    [queue addOperationWithBlock:^{
        NSLog(@"1-----%@", [NSThread currentThread]);
    }];
    
    [queue addOperationWithBlock:^{
        NSLog(@"2-----%@", [NSThread currentThread]);
    }];
    
    [queue addOperationWithBlock:^{
        NSLog(@"3-----%@", [NSThread currentThread]);
    }];
    
    [queue addOperationWithBlock:^{
        NSLog(@"4-----%@", [NSThread currentThread]);
    }];
    
    [queue addOperationWithBlock:^{
        NSLog(@"5-----%@", [NSThread currentThread]);
    }];

运行结果

2024-05-21 21:57:50.157582+0800 NSOperation[3588:106263] 1-----<NSThread: 0x600001c5f240>{number = 5, name = (null)}
2024-05-21 21:57:50.157608+0800 NSOperation[3588:106260] 2-----<NSThread: 0x600001c4ca00>{number = 6, name = (null)}
2024-05-21 21:57:50.157607+0800 NSOperation[3588:106258] 3-----<NSThread: 0x600001c5d480>{number = 4, name = (null)}
2024-05-21 21:57:50.157627+0800 NSOperation[3588:106257] 5-----<NSThread: 0x600001c56580>{number = 7, name = (null)}
2024-05-21 21:57:50.157611+0800 NSOperation[3588:106264] 4-----<NSThread: 0x600001c4d7c0>{number = 3, name = (null)}

可以看出:
使用addOperationWithBlock:将操作加入到操作队列后能够开启新线程,进行并发执行。

5,NSOperationQueue控制串行执行,并发执行

NSOperationQueue创建的自定义队列同时具有串行,并发功能。前面的队列都是并发功能,怎样实现串行功能?

队列的一个关键属性:maxConcurrentOperationCount, 最大并发操作数,用来控制一个特定队列中可以有多少个操作同时参与并发执行。

注意⚠️:maxConcurrentOperationCount控制的并不是并发线程的数量,而是一个队列中同时能并发执行的最大操作数。而且一个操作也并非只能在一个线程中运行。

  • maxConcurrentOperationCount默认情况为-1,表示不进行限制,可进行并发执行。
  • maxConcurrentOperationCount为1时,队列为串行队列。只能串行执行
  • maxConcurrentOperationCount大于1时队列为并发队列。操作并发执行,当然这个值不应超过系统的限制,即使自己设置一个很大的值,系统也会自动调整为mīn{自己设定的值,系统设定的默认最大值}
NSOperationQueue* queue  = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = 1;
     //queue.maxConcurrentOperationCount = 2;
    //queue.maxConcurrentOperationCount = 8;
    [queue addOperationWithBlock:^{
            for (int i = 0; i < 2; i++) {
                [NSThread sleepForTimeInterval:2]; // 模拟耗时操作
                NSLog(@"1---%@", [NSThread currentThread]); // 打印当前线程
            }
        }];
        [queue addOperationWithBlock:^{
            for (int i = 0; i < 2; i++) {
                [NSThread sleepForTimeInterval:2]; // 模拟耗时操作
                NSLog(@"2---%@", [NSThread currentThread]); // 打印当前线程
            }
        }];
        [queue addOperationWithBlock:^{
            for (int i = 0; i < 2; i++) {
                [NSThread sleepForTimeInterval:2]; // 模拟耗时操作
                NSLog(@"3---%@", [NSThread currentThread]); // 打印当前线程
            }
        }];
        [queue addOperationWithBlock:^{
            for (int i = 0; i < 2; i++) {
                [NSThread sleepForTimeInterval:2]; // 模拟耗时操作
                NSLog(@"4---%@", [NSThread currentThread]); // 打印当前线程
            }
        }];

当并发操作为1时运行结果:

2024-05-22 20:25:51.571321+0800 NSOperation[5261:255493] 1---<NSThread: 0x600000dd0280>{number = 7, name = (null)}
2024-05-22 20:25:53.578973+0800 NSOperation[5261:255493] 1---<NSThread: 0x600000dd0280>{number = 7, name = (null)}
2024-05-22 20:25:55.584167+0800 NSOperation[5261:255496] 2---<NSThread: 0x600000dc44c0>{number = 6, name = (null)}
2024-05-22 20:25:57.589578+0800 NSOperation[5261:255496] 2---<NSThread: 0x600000dc44c0>{number = 6, name = (null)}
2024-05-22 20:25:59.594866+0800 NSOperation[5261:255493] 3---<NSThread: 0x600000dd0280>{number = 7, name = (null)}
2024-05-22 20:26:01.596334+0800 NSOperation[5261:255493] 3---<NSThread: 0x600000dd0280>{number = 7, name = (null)}
2024-05-22 20:26:03.601618+0800 NSOperation[5261:255493] 4---<NSThread: 0x600000dd0280>{number = 7, name = (null)}
2024-05-22 20:26:05.606785+0800 NSOperation[5261:255493] 4---<NSThread: 0x600000dd0280>{number = 7, name = (null)}

当并发操作为2时运行结果:

2024-05-22 20:29:26.563109+0800 NSOperation[5419:260761] 1---<NSThread: 0x600001ea8040>{number = 7, name = (null)}
2024-05-22 20:29:26.564371+0800 NSOperation[5419:260765] 2---<NSThread: 0x600001efe4c0>{number = 3, name = (null)}
2024-05-22 20:29:28.567138+0800 NSOperation[5419:260761] 1---<NSThread: 0x600001ea8040>{number = 7, name = (null)}
2024-05-22 20:29:28.568175+0800 NSOperation[5419:260765] 2---<NSThread: 0x600001efe4c0>{number = 3, name = (null)}
2024-05-22 20:29:30.572397+0800 NSOperation[5419:260767] 3---<NSThread: 0x600001efe380>{number = 6, name = (null)}
2024-05-22 20:29:30.573421+0800 NSOperation[5419:260765] 4---<NSThread: 0x600001efe4c0>{number = 3, name = (null)}
2024-05-22 20:29:32.575165+0800 NSOperation[5419:260765] 4---<NSThread: 0x600001efe4c0>{number = 3, name = (null)}
2024-05-22 20:29:32.577935+0800 NSOperation[5419:260767] 3---<NSThread: 0x600001efe380>{number = 6, name = (null)}

可以看出:
当最大操作并发数为1时,操作是按顺序串行执行的,并且一个操作完成之后,下一个操作,才开始执行操作。当最大操作并发数为2时,操作是并发执行的,可以同时执行两个操作。而且开启线程的数量有系统决定的,不用我们自己管理。

6,NSOperation操作依赖

NSOperation、NSOperationQueue 与GCD不同的是它能添加操作之间的依赖关系。通过操作依赖关系,我们可以方便的控制操作之间的执行先后顺序。

NSOperation3个管理和查看依赖的接口

  • - (void)addDependency:(NSOperation *)op; 添加依赖,是当前操作依赖于操作op的完成
  • - (void)removeDependency:(NSOperation *)op; 移除依赖,取消当前操作对操作op的依赖
  • @property (readonly, copy) NSArray<NSOperation *> *dependencies;在当前操作开始执行之前完成执行的所有操作对象数组

通过添加依赖,我们可以控制操作之间的执行顺序

NSOperationQueue* queue = [[NSOperationQueue alloc] init];
    NSBlockOperation* op1 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2];
            NSLog(@"1----%@", [NSThread currentThread]);
        }
    }];
    NSBlockOperation* op2 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2];
            NSLog(@"2----%@", [NSThread currentThread]);
        }
    }];
    [op2 addDependency:op1];
    [queue addOperation:op1];
    [queue addOperation:op2];

运行结果:

2024-05-22 20:52:57.885391+0800 NSOperation[5788:276470] 1----<NSThread: 0x60000113aa00>{number = 6, name = (null)}
2024-05-22 20:52:59.889382+0800 NSOperation[5788:276470] 1----<NSThread: 0x60000113aa00>{number = 6, name = (null)}
2024-05-22 20:53:01.895365+0800 NSOperation[5788:276473] 2----<NSThread: 0x600001140100>{number = 3, name = (null)}
2024-05-22 20:53:03.898759+0800 NSOperation[5788:276473] 2----<NSThread: 0x600001140100>{number = 3, name = (null)}

可以看出:
通过添加依赖,操作不在是并发执行,无论运行几次,都是op1先执行,op2后执行。

7,NSoperation优先级

NSOperation提供了queuePriority优先级属性,queuePriority属性适用于同一操作队列中的操作,不适用于不同操作队列中的操作。默认情况下,所有新建的操作对象优先级都是NSOperationQueuePriorityNormal。但是我们可以通过setqueuePriority:方法来改变当前操作在同一队列中的执行优先级。

// 优先级的取值
typedef NS_ENUM(NSInteger, NSOperationQueuePriority) {
    NSOperationQueuePriorityVeryLow = -8L,
    NSOperationQueuePriorityLow = -4L,
    NSOperationQueuePriorityNormal = 0,
    NSOperationQueuePriorityHigh = 4,
    NSOperationQueuePriorityVeryHigh = 8
};

前面说过:
对于添加到队列中的操作,首先进入准备就绪的状态(就绪状态取决于操作之间的依赖关系),然后进入就绪状态的操作的开始执行顺序由操作之间的优先级决定,(优先级是操作对象的自身属性)。

  • 操作的准备就绪状态:当一个操作的所有以依赖都已经完成时,操作对象会进入准备就绪状态,等待执行。

下面了解queuePriority属性的作用对象

  • queuePriority属性决定了进入准备就绪状态操作之间的执行顺序。队列先执行高优先级的操作。优先级不能取代依赖关系
  • 一个队列既包括了准备就绪状态的操作,由包含了未准备就绪状态的操作,未准备就绪的操作优先级高于准备就绪状态的操作。但是,虽然准备就绪的操作优先级低,也会优先执行。这说明,优先级不能取代依赖关系。如果要控制操作间的启动顺序,则必须使用依赖关系
 
    NSOperationQueue* queue = [[NSOperationQueue alloc] init];
    NSBlockOperation* op1 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            NSLog(@"1----%@", [NSThread currentThread]);
            
        }
        
    }];
    NSBlockOperation* op2 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            NSLog(@"2----%@", [NSThread currentThread]);
            
        }
    }];
    NSBlockOperation* op3 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"3----%@", [NSThread currentThread]);
            
    }];
    [op2 addDependency:op1];
    op3.queuePriority = NSOperationQueuePriorityHigh;
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];

运行结果:

2024-05-22 21:38:42.733158+0800 NSOperation[6669:310514] 3----<NSThread: 0x600000568cc0>{number = 5, name = (null)}
2024-05-22 21:38:42.733163+0800 NSOperation[6669:310513] 1----<NSThread: 0x600000578000>{number = 7, name = (null)}
2024-05-22 21:38:44.738757+0800 NSOperation[6669:310513] 1----<NSThread: 0x600000578000>{number = 7, name = (null)}
2024-05-22 21:38:46.744443+0800 NSOperation[6669:310514] 2----<NSThread: 0x600000568cc0>{number = 5, name = (null)}
2024-05-22 21:38:48.745032+0800 NSOperation[6669:310514] 2----<NSThread: 0x600000568cc0>{number = 5, name = (null)}

使op3的优先级高于op1,所以操作的执行顺序为op3->op1->op2;

注意⚠️:这里的优先级只是决定操作开始执行的先后顺序,不能决定整体的执行顺序,而依赖就可以决定操作间的整体执行顺序

有时我们设置了优先级,但是却没有按照优先级大小来执行操作

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

有时的运行结果:

2024-05-26 20:01:08.509770+0800 NSOperation[41338:1500095] 1----<NSThread: 0x600000605600>{number = 5, name = (null)}
2024-05-26 20:01:08.509770+0800 NSOperation[41338:1500101] 3----<NSThread: 0x600000619900>{number = 6, name = (null)}
2024-05-26 20:01:08.509851+0800 NSOperation[41338:1500099] 2----<NSThread: 0x600000604100>{number = 3, name = (null)}

还可以设置NSOperation的qualityOfService属性来设置操作在队列中的服务质量
(iOS8 以后苹果推荐使用服务质量替代优先级)

typedef NS_ENUM(NSInteger, NSQualityOfService) {
    NSQualityOfServiceUserInteractive = 0x21,
    NSQualityOfServiceUserInitiated = 0x19,
    NSQualityOfServiceUtility = 0x11,
    NSQualityOfServiceBackground = 0x09,
    NSQualityOfServiceDefault = -1
} 

@property NSQualityOfService qualityOfService;
NSOperationQueue* queue = [[NSOperationQueue alloc] init];
     NSBlockOperation* op1 = [NSBlockOperation blockOperationWithBlock:^{
     
     
     NSLog(@"1----%@", [NSThread currentThread]);
     
     }];
     NSBlockOperation* op2 = [NSBlockOperation blockOperationWithBlock:^{
     
     
     NSLog(@"2----%@", [NSThread currentThread]);
     
     }];
     NSBlockOperation* op3 = [NSBlockOperation blockOperationWithBlock:^{
     
     
     NSLog(@"3----%@", [NSThread currentThread]);
     }];
    
    op3.qualityOfService = NSQualityOfServiceUserInteractive;
    op1.qualityOfService = NSQualityOfServiceDefault;
    
    [op2 addDependency:op1];
     
     
     [queue addOperation:op1];
     [queue addOperation:op2];
     [queue addOperation:op3];

但是依然会出现op1先执行的情况
质量服务等级 (qualityOfService) 决定了操作的优先级,高优先级的操作通常会比低优先级的操作更早被调度。然而,如果高优先级的操作和低优先级的操作同时准备好执行,队列仍然会根据它们的添加顺序来决定先执行哪一个。

总之,优先级和服务质量都不能保证操作开始执行的顺序的决定性,只是改变其先执行或后执行的概率。

8,NSOperation,NSOperationQueue线程间的通信

在iOS开发中,我们一般在主线程进行UI刷新,例如:点击,滚动拖拽等事件。我们通常把一些耗时的操作放在其他线程,比如图片下载,文件上传操作。而我们有时在其他线程完成了耗时操作时,需要回到主线程,那么就用到了线程之间的通信。

 NSOperationQueue* queue = [[NSOperationQueue alloc] init];
    
    [queue addOperationWithBlock:^{
        //异步进行耗时操作
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2];
            NSLog(@"1------%@",[NSThread currentThread]);
        }
        //回到主线程进行UI刷新
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            for (int i = 0; i < 2; i++) {
                [NSThread sleepForTimeInterval:2];
                NSLog(@"2------%@",[NSThread currentThread]);
            }
        }];
    }];

运行结果:

2024-05-24 09:32:25.423376+0800 NSOperation[27229:1025696] 1------<NSThread: 0x60000387a7c0>{number = 6, name = (null)}
2024-05-24 09:32:27.429079+0800 NSOperation[27229:1025696] 1------<NSThread: 0x60000387a7c0>{number = 6, name = (null)}
2024-05-24 09:32:29.430900+0800 NSOperation[27229:1025623] 2------<_NSMainThread: 0x600003830280>{number = 1, name = main}
2024-05-24 09:32:31.432540+0800 NSOperation[27229:1025623] 2------<_NSMainThread: 0x600003830280>{number = 1, name = main}

可以看出:
通过线程间的通信,现在其他线程执行操作,等操作执行完毕之后在回到主线程执行主线程的相应操作

9,NSOperation,NSOperationQueue线程同步和线程安全

  • 线程安全:如果代码所在的进程中有多个线程同时进行,而这些线程可能会同时运行这段代码。如果每次运行的结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的是一样的,就是线程安全的。若每个线程中对全局变量,静态变量只有读操作,没有写操作,一般来说,这个全局变量是线程安全的;若有多个线程同时执行写操作(更改变量),一般要考虑线程同步,否则的话就会影响线程安全。
  • 线程同步:可理解为线程A和线程B一块配合,A执行到一定程度时要依赖线程B的某个结果,于是线程A停下来,示意B运行;B执行后将结果给A;A在继续操作。

下面看一看非线程安全案例;

/**
 * 非线程安全:不使用 NSLock
 * 初始化火车票数量、卖票窗口(非线程安全)、并开始卖票
 */

    NSLog(@"currentThread---%@",[NSThread currentThread]); // 打印当前线程

    self.ticketSurplusCount = 50;

    // 1.创建 queue1,queue1 代表北京火车票售卖窗口
    NSOperationQueue *queue1 = [[NSOperationQueue alloc] init];
    queue1.maxConcurrentOperationCount = 1;

    // 2.创建 queue2,queue2 代表上海火车票售卖窗口
    NSOperationQueue *queue2 = [[NSOperationQueue alloc] init];
    queue2.maxConcurrentOperationCount = 1;

    // 3.创建卖票操作 op1
    __weak typeof(self) weakSelf = self;
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        [weakSelf saleTicketNotSafe];
    }];

    // 4.创建卖票操作 op2
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        [weakSelf saleTicketNotSafe];
    }];

    // 5.添加操作,开始卖票
    [queue1 addOperation:op1];
    [queue2 addOperation:op2];

/**
 * 售卖火车票(非线程安全)
 */
- (void)saleTicketNotSafe {
    while (1) {

        if (self.ticketSurplusCount > 0) {
            //如果还有票,继续售卖
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        } else {
            NSLog(@"所有火车票均已售完");
            break;
        }
    }
}

输出结果:

2024-05-24 11:48:49.628486+0800 NSOperation[28392:1064891] 剩余票数:10 窗口:<NSThread: 0x600003f08180>{number = 6, name = (null)}
2024-05-24 11:48:49.628534+0800 NSOperation[28392:1064897] 剩余票数:9 窗口:<NSThread: 0x600003f40b00>{number = 4, name = (null)}
2024-05-24 11:48:49.628581+0800 NSOperation[28392:1064891] 剩余票数:8 窗口:<NSThread: 0x600003f08180>{number = 6, name = (null)}
2024-05-24 11:48:49.628687+0800 NSOperation[28392:1064891] 剩余票数:6 窗口:<NSThread: 0x600003f08180>{number = 6, name = (null)}
2024-05-24 11:48:49.628687+0800 NSOperation[28392:1064897] 剩余票数:7 窗口:<NSThread: 0x600003f40b00>{number = 4, name = (null)}
2024-05-24 11:48:49.628735+0800 NSOperation[28392:1064891] 剩余票数:5 窗口:<NSThread: 0x600003f08180>{number = 6, name = (null)}
2024-05-24 11:48:49.628871+0800 NSOperation[28392:1064897] 剩余票数:3 窗口:<NSThread: 0x600003f40b00>{number = 4, name = (null)}
2024-05-24 11:48:49.628874+0800 NSOperation[28392:1064891] 剩余票数:4 窗口:<NSThread: 0x600003f08180>{number = 6, name = (null)}
2024-05-24 11:48:49.628981+0800 NSOperation[28392:1064897] 剩余票数:2 窗口:<NSThread: 0x600003f40b00>{number = 4, name = (null)}
2024-05-24 11:48:49.629021+0800 NSOperation[28392:1064891] 剩余票数:1 窗口:<NSThread: 0x600003f08180>{number = 6, name = (null)}
2024-05-24 11:48:49.629118+0800 NSOperation[28392:1064897] 剩余票数:0 窗口:<NSThread: 0x600003f40b00>{number = 4, name = (null)}
2024-05-24 11:48:49.629302+0800 NSOperation[28392:1064891] 所有火车票均已售完
2024-05-24 11:48:49.629411+0800 NSOperation[28392:1064897] 所有火车票均已售完

得到的票数是错乱的,不符合我们的需求。

线程安全的解决方案:可以个线程加锁,在一个线程执行该操作时,不允许其他线程进行操作。

这里我们使用 NSLock 对象来解决线程同步问题。NSLock 对象可以通过进入锁时调用 lock 方法,解锁时调用 unlock 方法来保证线程安全。

- (void)saleTicketSafe {
    while (1) {

        // 加锁
        [self.lock lock];

        if (self.ticketSurplusCount > 0) {
            //如果还有票,继续售卖
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        }

        // 解锁
        [self.lock unlock];

        if (self.ticketSurplusCount <= 0) {
            NSLog(@"所有火车票均已售完");
            break;
        }
    }
}

运行结果:

2024-05-26 19:51:18.819260+0800 NSOperation[41094:1491149] 剩余票数:9 窗口:<NSThread: 0x6000022b7000>{number = 8, name = (null)}
2024-05-26 19:51:18.819269+0800 NSOperation[41094:1491148] 剩余票数:8 窗口:<NSThread: 0x6000022bc8c0>{number = 7, name = (null)}
2024-05-26 19:51:19.024334+0800 NSOperation[41094:1491149] 剩余票数:7 窗口:<NSThread: 0x6000022b7000>{number = 8, name = (null)}
2024-05-26 19:51:19.024341+0800 NSOperation[41094:1491148] 剩余票数:6 窗口:<NSThread: 0x6000022bc8c0>{number = 7, name = (null)}
2024-05-26 19:51:19.229399+0800 NSOperation[41094:1491149] 剩余票数:5 窗口:<NSThread: 0x6000022b7000>{number = 8, name = (null)}
2024-05-26 19:51:19.229416+0800 NSOperation[41094:1491148] 剩余票数:4 窗口:<NSThread: 0x6000022bc8c0>{number = 7, name = (null)}
2024-05-26 19:51:19.434466+0800 NSOperation[41094:1491148] 剩余票数:3 窗口:<NSThread: 0x6000022bc8c0>{number = 7, name = (null)}
2024-05-26 19:51:19.434466+0800 NSOperation[41094:1491149] 剩余票数:2 窗口:<NSThread: 0x6000022b7000>{number = 8, name = (null)}
2024-05-26 19:51:19.639536+0800 NSOperation[41094:1491148] 剩余票数:1 窗口:<NSThread: 0x6000022bc8c0>{number = 7, name = (null)}
2024-05-26 19:51:19.639556+0800 NSOperation[41094:1491149] 剩余票数:0 窗口:<NSThread: 0x6000022b7000>{number = 8, name = (null)}
2024-05-26 19:51:19.844631+0800 NSOperation[41094:1491148] 所有火车票均已售完
2024-05-26 19:51:19.844643+0800 NSOperation[41094:1491149] 所有火车票均已售完

10, NSOperation、NSOperationQueue 常用属性和方法归纳

10.1 NSOperation 常用属性和方法

取消操作方法

  • (void)cancel; 可取消操作,实质是标记 isCancelled 状态。

判断操作状态方法

  • (BOOL)isFinished; 判断操作是否已经结束。
  • (BOOL)isCancelled; 判断操作是否已经标记为取消。
  • (BOOL)isExecuting; 判断操作是否正在在运行。
  • (BOOL)isReady; 判断操作是否处于准备就绪状态,这个值和操作的依赖关系相关。

操作同步

  • (void)waitUntilFinished; 阻塞当前线程,直到该操作结束。可用于线程执行顺序的同步。
  • (void)setCompletionBlock:(void (^)(void))block; completionBlock 会在当前操作执行完毕时执行 completionBlock。
  • (void)addDependency:(NSOperation *)op; 添加依赖,使当前操作依赖于操作 op 的完成。
  • (void)removeDependency:(NSOperation *)op; 移除依赖,取消当前操作对操作 op 的依赖。
    @property (readonly, copy) NSArray<NSOperation *> *dependencies; 在当前操作开始执行之前完成执行的所有操作对象数组。

10.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; 获取主队列。

注意

这里的暂停和取消(包括操作的取消和队列的取消)并不代表可以将当前的操作立即取消,而是当当前的操作执行完毕之后不再执行新的操作。
暂停和取消的区别就在于:暂停操作之后还可以恢复操作,继续向下执行;而取消操作之后,所有的操作就清空了,无法再接着执行剩下的操作。

  • 14
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在网络编程中,多线程编程是一种常用的技术,可以提高程序的并发性和性能。下面是一些关于多线程编程的常用方法和注意事项: 1. NSThread:NSThread是iOS中最底层的线程类,它可以通过类方法或实例方法来创建线程。使用NSThread可以设置线程的名称、优先级,以及控制线程的睡眠和退出等操作。 2. 线程调度:在多线程编程中,多个线程会并发运行,但线程的执行顺序是由CPU调度器决定的,程序员无法控制。多个线程会同时竞争CPU资源,谁先抢到资源谁就先执行,所以多线程的执行顺序是随机的。 3. 多线程的创建:在iOS开发中,常用的多线程编程方式有三种:NSThread、GCD和NSOperation。NSThread是最底层的线程类,可以直接操作线程的各种属性和方法。GCD(Grand Central Dispatch)提供了一种高效的并发编程模型,可以通过队列来管理任务的执行。NSOperation是基于GCD的更高层次的封装,提供了更多的控制和管理线程的功能。 4. 线程的创建顺序:在多线程编程中,并不能保证哪个线程会先运行,即无法确定新创建的线程或调用线程哪个会先执行。新创建的线程可以访问进程的地址空间,并继承调用线程的浮点环境和信号屏蔽字,但挂起信号集会被清除。 总结来说,多线程编程是一种提高程序并发性和性能的技术,在网络编程中尤为重要。通过使用NSThread、GCD或NSOperation等方法,可以实现多线程的创建和管理。然而,程序员无法控制线程的执行顺序,因为线程的调度是由CPU调度器决定的。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [IOS之多线程基础(OC)](https://blog.csdn.net/yong_19930826/article/details/105857055)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [UNIX环境高级编程笔记](https://blog.csdn.net/w_x_myself/article/details/128613534)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值