- 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)}
打印结果显示也是并发执行的
如果使用blockOperationWithBlock
和NSInvocationOperation
创建的操作中代码非常多, 可以使用自定义的子类继承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顺序执行任务, 而不是只开启一条线程
队列的状态: 队列中的任务也是有状态的: 已经执行完毕的 | 正在执行 | 队列等待状态
- 暂停
[queue setSuspended:YES]
, 可以恢复继续执行[queue setSuspended:NO]
, 不能暂停正在继续执行的任务 - 取消
[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}