iOS开发代码段iOS技术难点iOS基础

iOS之多线程(全)

2016-04-08  本文已影响684人  李小南

很多人都写过多线程的文章,今天我也来小小的总结一下:

多线程基本概念

NSThread(偶尔使用)

使用最多的就是[NSThread currentThread]打印当前线程
1.使用NSThread创建线程的几种方法:

 //创建线程的几种方法
 - (void)createNewThread1
{
    //1.创建线程
    /*
     第一个参数:目标对象 self
     第二个参数:方法选择器 调用方法的名称
     第三个参数:调用方法的参数 没有着传值nil
     */
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"线程A"];
    //线程的名称
    thread.name = @"线程A";
    //线程的优先级-------越高说明被CPU调用的概率越大
    thread.threadPriority = 0.9;    //0.0~1.0 1.0是最高,默认是0.5
    //开启线程
    [thread start];
    
    NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"线程B"];
    //线程的名称
    thread1.name = @"线程B";
    //线程的优先级
    thread1.threadPriority = 0.5;    //0.0~1.0 1.0是最高,默认是0.5
    //开启线程
    [thread1 start];
    
    NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"线程C"];
    //线程的名称
    thread2.name = @"线程C";
    //线程的优先级
    thread2.threadPriority = 0.1;    //0.0~1.0 1.0是最高,默认是0.5
    //开启线程
    [thread2 start];
    
}

- (void)createNewThread2
{
    //detach:分离
    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"分离出一条线程"];
}


- (void)createNewThread3
{
    //是NSObject的一个分类方法
    [self performSelectorInBackground:@selector(run:) withObject:@"创建后台线程"];
}

//自定义创建线程
- (void)createNewThread4
{
    //创建这种线程的时候,会调用自身重写的main方法
    LXNThread *thread = [[LXNThread alloc] init];
    [thread start];
}

/*注意:
 //优先级高的线程不一定是先执行完毕(因为不同线程的执行方法的长短不一样)
 //1 10
 //2 1
 //3 0.1
 //当线程中所有的任务都执行完毕的时候线程会被释放----线程死不能复生.
 */
- (void)run:(NSString *)parma
{
    for (int i = 0; i < 10; i++) {
        NSLog(@"-%@--%@", [NSThread currentThread].name, parma);
    }
}

2.线程的安全(加锁)

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //初始化总票数
    self.totalNumber = 100;
    
    //创建线程
    self.threadA = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    self.threadA.name = @"售票员A";
    
    self.threadB = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    self.threadB.name = @"售票员B";
    
    self.threadC = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    self.threadC.name = @"售票员C";
    
    //执行线程
    [self.threadA start];
    [self.threadB start];
    [self.threadC start];
}


- (void)run
{
    //卖票
    while (1) {
        //加锁
        //1.锁对象必须是同一个,加多把锁是无效的
        //2.锁对象只要的唯一的都可以,self
        //3.加锁需要注意位置
        //4.不要乱加锁,加锁的前提条件:多个线程访问同一个资源
        //5.加锁是需要耗费性能的
        @synchronized(self) {
            int count = self.totalNumber;
            
            if (count > 0) {
                
                //耗时操作
                for (int i = 0; i < 10000; i++) {
                    
                }
                
                self.totalNumber = count - 1;   //99 == 100 - 1
                NSLog(@"%@卖出一张票,还剩多少张%d", [NSThread currentThread].name, self.totalNumber);
            } else {
                NSLog(@"票卖光了,做大鸟回家吧");
                break;
            }
        }
    }
}

3.线程间的通信(在子线程中下载一张图片,在主线程中显示)

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //创建线程
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downLoad) object:nil];
    
    [thread start];
}


- (void)downLoad
{
    //1.确定url
    NSURL *url = [NSURL URLWithString:@"http://v1.qzone.cc/pic/201407/13/11/05/53c1f77cdbd01600.jpg%21600x600.jpg"];
    //2.下载图片的二进制数据到本地
    NSData *data = [NSData dataWithContentsOfURL:url];
    //3.将二进制数据转换成图片
    UIImage *image = [UIImage imageWithData:data];
    NSLog(@"-------");
    //4.回到主线程中刷新UI
    /*
     第一个参数:调用的方法
     第二个参数:调用方法需要传递的参数
     第三个参数:是否等待调用的方法执行完毕
     */
//    [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];
//    [self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
    
    //(取巧的方法)前面是什么调用,就去那个类里面找这个方法
    [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
    
    NSLog(@"----%@", [NSThread currentThread]);
}

- (void)showImage:(UIImage *)image
{
    self.imageView.image = image;
    NSLog(@"---UI---%@", [NSThread currentThread]);
}

GCD(经常使用)

全称是Grand Central Dispatch,可译为“牛逼的中枢调度器”,纯C语言,提供了非常多强大的函数

1.GCD的基本使用


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self syncMian];
}

//异步函数 + 主队列:不会开线程,所有的任务串行执行
- (void)asyncMian
{
    //1.获取主队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    NSLog(@"start------");
    
    //2.使用异步函数添加任务到队列中
    dispatch_async(queue, ^{
        NSLog(@"1----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"2----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"3----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"4----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"5----%@", [NSThread currentThread]);
    });
}

//同步函数 + 主队列:会锁死
- (void)syncMian
{
    //1.获取主队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    NSLog(@"start------");
    
    //2.使用异步函数添加任务到队列中
    dispatch_sync(queue, ^{
        NSLog(@"1----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"2----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"3----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"4----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"5----%@", [NSThread currentThread]);
    });
}



//异步函数 + 并发队列
/*
 //会不会开线程:会
 //如果开线程,那么开几条?多条(并不是有几个任务就开几条线程)
 //队列内部任务如何执行:并发
 */
- (void)asyncConCurrent    //ConCurrent:同时存在的
{
    //1.创建队列-----这时C语言,不能用OC得字符串
    //dispatch_queue_t queue = dispatch_queue_create("com.lixioanan.www.download", DISPATCH_QUEUE_CONCURRENT);
    
    //获取全局并发队列
    /*
     第一个参数:优先级
     第二个参数:留给未来使用的0
     */
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    NSLog(@"start------");
    
    //2.使用异步函数添加任务到队列中
    dispatch_async(queue, ^{
        NSLog(@"1----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"2----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"3----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"4----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"5----%@", [NSThread currentThread]);
    });
}

//异步函数 + 串型队列
/*
 //会不会开线程:会
 //如果开线程,那么开几条? 1
 //队列内部任务如何执行:串行
 */
- (void)asyncSerial    //Serial:串行
{
    //1.创建队列-----这时C语言,不能用OC得字符串
    /*
     第一个参数:标签 队列的名称 C语言
     第二个参数:队列的类型
     */
    dispatch_queue_t queue = dispatch_queue_create("com.lixioanan.www.download", DISPATCH_QUEUE_SERIAL);
    
    
    //2.使用异步函数添加任务到队列中
    //该方法完成了以下操作:1)封装任务 2)把任务添加到队列
    dispatch_async(queue, ^{
        NSLog(@"1----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"2----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"3----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"4----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"5----%@", [NSThread currentThread]);
    });
}


//同步函数 + 并发队列
/*
 //会不会开线程:不会
 //如果开线程,那么开几条?
 //队列内部任务如何执行:串行
 */
- (void)syncConCurrent
{
    //1.创建队列-----这时C语言,不能用OC得字符串
    /*
     第一个参数:标签 队列的名称 C语言
     第二个参数:队列的类型
     */
    dispatch_queue_t queue = dispatch_queue_create("com.lixioanan.www.download", DISPATCH_QUEUE_CONCURRENT);
    
    
    //2.使用异步函数添加任务到队列中
    //该方法完成了以下操作:1)封装任务 2)把任务添加到队列
    dispatch_sync(queue, ^{
        NSLog(@"1----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"2----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"3----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"4----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"5----%@", [NSThread currentThread]);
    });
}



//同步函数 + 串行队列
/*
 //会不会开线程:不会
 //如果开线程,那么开几条?
 //队列内部任务如何执行:串行
 */
- (void)syncSerial
{
    //1.创建队列-----这时C语言,不能用OC得字符串
    /*
     第一个参数:标签 队列的名称 C语言
     第二个参数:队列的类型
     */
    dispatch_queue_t queue = dispatch_queue_create("com.lixioanan.www.download", DISPATCH_QUEUE_SERIAL);
    
    
    //2.使用异步函数添加任务到队列中
    //该方法完成了以下操作:1)封装任务 2)把任务添加到队列
    dispatch_sync(queue, ^{     //会锁死.
        NSLog(@"1----%@", [NSThread currentThread]);
        dispatch_sync(queue, ^{
            NSLog(@"------oooo--%@", [NSThread currentThread]);
        });
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"2----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"3----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"4----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"5----%@", [NSThread currentThread]);
    });
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self moveFile];
}


//延迟执行
- (void)delay
{
    NSLog(@"------");
    
    //1
//    [self performSelector:@selector(test) withObject:nil afterDelay:2.0];
    
    //2.定时器
//    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:NO];
    
    
    //3
    /*
     第一个参数:DISPATCH_TIME_NOW 从什么时候开始计时
     第二个参数:延迟的时间 2.0表示2秒 GCD的时间是以纳秒为单位
     第三个参数:队列
     dispatch_get_main_queue()  主线程,在主线程中执行
     如果是其他队列(并发|串行),那么block在子线程中调用
     */
    
    //即使是串行队列,block也在子线程中调用
    dispatch_queue_t queue = dispatch_queue_create("luanxie", DISPATCH_QUEUE_SERIAL);
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), queue, ^{
        NSLog(@"%@", [NSThread currentThread]);
    });
    
    
}


//栅栏函数
//知识点:barrier在使用的时候不能使用全局并发队列
- (void)barrier
{
    //创建并发队列
    dispatch_queue_t queue = dispatch_queue_create("luanxie", DISPATCH_QUEUE_CONCURRENT);
    
    //栅栏函数中使用全局并发队列后..栅栏函数的block会最先执行
//    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    dispatch_async(queue, ^{
        for (int i = 0; i < 10; i++) {
            NSLog(@"download1--%@", [NSThread currentThread]);
        }
    });
    dispatch_async(queue, ^{
        for (int i = 0; i < 10; i++) {
            NSLog(@"download2--%@", [NSThread currentThread]);
        }
    });
    
    //1.在子线程中执行
    //2.开始执行之前确保前面的任务1和任务2都已经执行完毕
    //3.只有当我执行完毕之后才能继续执行后面的任务
    dispatch_barrier_sync(queue, ^{      //用异步就在子线程中执行,用同步就在主线程中执行
        NSLog(@"barrier--%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        for (int i = 0; i < 10; i++) {
            NSLog(@"download3--%@", [NSThread currentThread]);
        }
    });
    dispatch_async(queue, ^{
        for (int i = 0; i < 10; i++) {
            NSLog(@"download4--%@", [NSThread currentThread]);
        }
    });
    
}


//一次性代码-----用在单例中
/*
 1)整个应用程序中只会执行一次
 2)本身是线程安全的
 */
- (void)once
{
    //一次性代码函数--在主线程中执行
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"%@", [NSThread currentThread]);
    });
}


//快速迭代
- (void)apply
{
    //串行执行
//    for (int i = 0; i < 10; i++) {
//        NSLog(@"%@", [NSThread currentThread]);
//    }
    
    
    /*
     第一个参数:迭代的次数
     第二个参数:队列
     注意:主线程也会参与迭代的过程,里面的任务是并发执行的
     !!!!不能传主队列---会锁死
     */
    //注意:传的是串行队列时,是主线程串行执行-----传的是并发队列时,是并发执行,
    dispatch_queue_t queue = dispatch_queue_create("luanxie", DISPATCH_QUEUE_SERIAL);
    
    NSLog(@"---");
    dispatch_apply(10, dispatch_get_main_queue(), ^(size_t index) {
        NSLog(@"%ld----%@",index, [NSThread currentThread]);
    });
    
}


//裁剪转移文件
- (void)moveFile
{
    //文件路径
    NSString *sourePath = @"/Users/lixiaonan/Desktop/form";
    
    //目标路径
    NSString *targetPath = @"/Users/lixiaonan/Desktop/to";
    
    //取出所有的文件
    NSArray *subPath = [[NSFileManager defaultManager] subpathsAtPath:sourePath];
    
    NSLog(@"%@", subPath);
    
    //快速迭代
    dispatch_apply(subPath.count, dispatch_get_global_queue(0, 0), ^(size_t index) {
        //目标文件
        NSString *sub = subPath[index];
        
        NSString *sourceFullPath = [sourePath stringByAppendingPathComponent:sub];
        
        NSString *targetFullPath = [targetPath stringByAppendingPathComponent:sub];
        
        [[NSFileManager defaultManager] moveItemAtPath:sourceFullPath toPath:targetFullPath error:nil];
        
        NSLog(@"%@", [NSThread currentThread]);
    });
}

- (void)test
{
    NSLog(@"-----");
}

NSOperation(经常使用)

1.相关概念

    01 NSOperation是对GCD的包装
    02 两个核心概念【队列+操作】

2.基本使用

    01 NSOperation本身是抽象类,只能只有它的子类
    02 三个子类分别是:NSBlockOperation、NSInvocationOperation以及自定义继承自NSOperation的类
    03 NSOperation和NSOperationQueue结合使用实现多线程并发
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self customOperation];
}


- (void)invocationOpertion
{
    
    //1.封装操作
    /*
     第一个参数:目标对象 self
     第二个参数:调用的方法
     第三个参数:调用方法需要传递的参数
     */
    NSInvocationOperation *invocaton = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download1) object:nil];
    //开始执行
    [invocaton start];
    
    //1.封装操作
    NSInvocationOperation *invocaton1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download1) object:nil];
    //开始执行
    [invocaton1 start];
    
    //1.封装操作
    NSInvocationOperation *invocaton2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download1) object:nil];
    //开始执行
    [invocaton2 start];
}


- (void)blockOperation
{
    //1.封装操作
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"%@", [NSThread currentThread]);
    }];
    
    [operation start];
    
    //1.封装操作
    NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"%@", [NSThread currentThread]);
    }];
    
    [operation1 start];
    
    //1.封装操作
    NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"%@", [NSThread currentThread]);
    }];
    
    //追加操作
    //如果操作里面的任务数量大于一,那么会开子线程一起执行
    [operation2 addExecutionBlock:^{
        NSLog(@"2----%@", [NSThread currentThread]);
    }];
    [operation2 addExecutionBlock:^{
        NSLog(@"2----%@", [NSThread currentThread]);
    }];
    [operation2 addExecutionBlock:^{
        NSLog(@"2----%@", [NSThread currentThread]);
    }];
    
    //要放在追加操作的后面
    [operation2 start];
}


- (void)customOperation
{
    //2.封装任务
    LXNOperation *operation = [[LXNOperation alloc] init];
    
    //2.开始执行
    //start --->main
    [operation start];
}

- (void)download1
{
    NSLog(@"%@", [NSThread currentThread]);
}

  - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self custom];
}


- (void)invocation
{
    //封装操作
    NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download1) object:nil];
    NSInvocationOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download2) object:nil];
    NSInvocationOperation *op3 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download3) object:nil];
    
    
    //创建队列
    /*
     GCD:
     并发队列:create | 全局并发队列
     串行队列:create | 主队列
     
     NSOperationQueue:
     主队列:是串行队列 [NSOperationQueue mainQueue](会在主线程中执行)
     非主队列:特殊(同时具备了并发和串行的功能),默认是并发队列[[NSOperationQueue alloc]init]
            通过设置(最大并发线程数)控制是串行还是并发
     */
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    //将操作添加到队列(会开启线程)
    [queue addOperation:op1];//--->start-->main
    [queue addOperation:op2];
    [queue addOperation:op3];
    
}

- (void)block
{
    //封装操作
    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 addExecutionBlock:^{
        NSLog(@"4-----%@", [NSThread currentThread]);
    }];
    [op2 addExecutionBlock:^{
        NSLog(@"5-----%@", [NSThread currentThread]);
    }];
    [op2 addExecutionBlock:^{
        NSLog(@"6-----%@", [NSThread currentThread]);
    }];
    
    
    //创建队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    //添加操作到队列
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];
 
    
    //4.简便方法
    /*
     1)封装操作
     2)提交操作到队列
     */
    [queue addOperationWithBlock:^{
        NSLog(@"kuaisu-----%@", [NSThread currentThread]);
    }];
}


//有利于代码的复用
//有利于代码的隐蔽
- (void)custom
{
    //封装任务
    LXNOperation *op = [[LXNOperation alloc] init];
    
    //创建队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    //绘制行mian里面的代码(会开线程)
    [queue addOperation:op];
}


- (void)download1
{
    NSLog(@"1--%@", [NSThread currentThread]);
}


- (void)download2
{
    NSLog(@"2--%@", [NSThread currentThread]);
}

- (void)download3
{
    NSLog(@"3--%@", [NSThread currentThread]);
}

@interface ViewController ()
/** 队列*/
@property (nonatomic ,strong) NSOperationQueue *queue;
@end

@implementation ViewController
- (IBAction)suspendBtnClick:(id)sender
{
    //暂停,可以恢复
    //队列里面的任务是有状态的,不能暂停当前正在处于执行状态的操作
    [self.queue setSuspended:YES];
    
}
- (IBAction)resumBtnClick:(id)sender
{
    //恢复
    [self.queue setSuspended:NO];
}
- (IBAction)cancelBtnClick:(id)sender
{
    //取消所有的操作
    //不能取消当前正在处于执行状态的操作,只能取消后面处于等待状态的
    [self.queue cancelAllOperations];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self test3];
}

-(void)test
{
    //1.创建队列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    //设置最大并发数:同一时间可以处理多少个操作
    //maxConcurrentOperationCount
    //当maxConcurrentOperationCount == 1的时候是串行队列,默认是并发队列
    //maxConcurrentOperationCount == -1 默认值(最大值~不受限制)
    queue.maxConcurrentOperationCount = 1;
    
    //2.封装操作
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        for (NSInteger i = 0; i<10000; i++) {
            NSLog(@"1-%zd---%@",i,[NSThread currentThread]);
        }
        
        
    }];
    
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        for (NSInteger i = 0; i<10000; i++) {
            NSLog(@"2-%zd---%@",i,[NSThread currentThread]);
        }
    }];
    
    NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
        for (NSInteger i = 0; i<1000; i++) {
            NSLog(@"3-%zd---%@",i,[NSThread currentThread]);
        }
    }];
    
    NSBlockOperation *op4 = [NSBlockOperation blockOperationWithBlock:^{
        for (NSInteger i = 0; i<1000; i++) {
            NSLog(@"4-%zd---%@",i,[NSThread currentThread]);
        }
    }];
    
    NSBlockOperation *op5 = [NSBlockOperation blockOperationWithBlock:^{
        for (NSInteger i = 0; i<1000; i++) {
            NSLog(@"5-%zd---%@",i,[NSThread currentThread]);
        }
    }];
    
    NSBlockOperation *op6 = [NSBlockOperation blockOperationWithBlock:^{
        for (NSInteger i = 0; i<1000; i++) {
            NSLog(@"6-%zd---%@",i,[NSThread currentThread]);
        }
    }];
    
    //3.添加操作到队列
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];
    [queue addOperation:op4];
    [queue addOperation:op5];
    [queue addOperation:op6];
    
    self.queue = queue;

}

-(void)test2
{
    //1.创建队列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    XMGOperation *op1 = [[XMGOperation alloc]init];
    
    [queue addOperation:op1];
    
    self.queue = queue;
}

-(void)test3
{
    //1.创建队列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    //2.封装操作
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        for (NSInteger i = 0; i<10; i++) {
            NSLog(@"1-%zd---%@",i,[NSThread currentThread]);
        }
    }];
    
    
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        for (NSInteger i = 0; i<10; i++) {
            NSLog(@"2-%zd---%@",i,[NSThread currentThread]);
        }
    }];
    
    
    NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"3-%@",[NSThread currentThread]);
    }];
    
    NSBlockOperation *op4 = [NSBlockOperation blockOperationWithBlock:^{
        for (NSInteger i = 0; i<10; i++) {
            NSLog(@"4-%zd---%@",i,[NSThread currentThread]);
        }
    }];
    
    //添加操作监听
    op4.completionBlock = ^{
        NSLog(@"我已经完成啦,快点来使用我--%@",[NSThread currentThread]);
    };
    
    //1---->4--->2-->3
    //设置操作依赖
    //注意点:不能设置循环依赖
    [op1 addDependency:op4];
    //[op4 addDependency:op1];
    
    [op4 addDependency:op2];
    [op2 addDependency:op3];
    
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];
    [queue addOperation:op4];
    
}

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;


/** 图片1 */
@property (nonatomic, strong) UIImage *image1;
@property (nonatomic, strong) UIImage *image2;
@end

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self combine];
}
//下载一张图片
- (void)download
{
    
    //封装一个操作
    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"1----%@", [NSThread currentThread]);
        
        NSURL *url = [NSURL URLWithString:@"http://cdn.duitang.com/uploads/item/201510/04/20151004202823_2nkms.jpeg"];
        
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        UIImage *image = [UIImage imageWithData:data];
        
        
        //回到主线程刷新图片
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.imageView.image = image;
            
            NSLog(@"--ui---%@", [NSThread currentThread]);
        }];
        
    }];
    
    
    //创建一个队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    [queue addOperation:op];
}

//下载多张图片合成综合案例(设置操作依赖)
- (void)combine
{
    //封装一个操作
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"1----%@", [NSThread currentThread]);
        
        NSURL *url = [NSURL URLWithString:@"http://cdn.duitang.com/uploads/item/201510/04/20151004202823_2nkms.jpeg"];
        
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        self.image1 = [UIImage imageWithData:data];
        
        
    }];
    
    //封装一个操作
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"2----%@", [NSThread currentThread]);
        
        NSURL *url = [NSURL URLWithString:@"http://cdn.duitang.com/uploads/item/201510/04/20151004202823_2nkms.jpeg"];
        
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        self.image2 = [UIImage imageWithData:data];
        
        
    }];
    
    NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
        UIGraphicsBeginImageContext(CGSizeMake(240, 240));
        NSLog(@"3----%@", [NSThread currentThread]);
        
        [self.image1 drawInRect:CGRectMake(0, 0, 120, 240)];
        
        [self.image2 drawInRect:CGRectMake(0, 120, 120, 240)];
        
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            NSLog(@"--ui---%@", [NSThread currentThread]);
            
            self.imageView.image = image;
        }];
    }];
    
    //KVO监听op3操作是否完成..........
    [op3 addObserver:self forKeyPath:@"isFinished" options:NSKeyValueObservingOptionNew context:nil];
    
    //创建一个队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    //设置依赖
    [op3 addDependency:op1];
    [op3 addDependency:op2];
    
    
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(NSBlockOperation *)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    NSLog(@"%zd", change);
}

@end

GCD和NSOperation的对比

1)GCD是纯C语言的API,而操作队列则是Object-C的对象。
2)在GCD中,任务用块(block)来表示,而块是个轻量级的数据结构;相反操作队列中的『操作』NSOperation则是个更加重量级的Object-C对象。
3)具体该使用GCD还是使用NSOperation需要看具体的情况

NSOperation和NSOperationQueue相对GCD的好处有:
1)NSOperationQueue可以方便的调用cancel方法来取消某个操作,而GCD中的任务是无法被取消的(安排好任务之后就不管了)。
2)NSOperation可以方便的指定操作间的依赖关系。
3)NSOperation可以通过KVO提供对NSOperation对象的精细控制(如监听当前操作是否被取消或是否已经完成等)
4)NSOperation可以方便的指定操作优先级。操作优先级表示此操作与队列中其它操作之间的优先关系,优先级高的操作先执行,优先级低的后执行。
5)通过自定义NSOperation的子类可以实现操作重用,

上一篇下一篇

猜你喜欢

热点阅读