美文网首页
NSOperation 和 GCD 的区别

NSOperation 和 GCD 的区别

作者: 寂寞先森666 | 来源:发表于2019-04-04 10:23 被阅读0次


 NSOperationQueue是把GCD封装为OC语法,额外比GCD增加了几项新功能

第一、支持限制最大并发数

- (void)operationQueueMaxConcurrentOperationCount

{

    //1:创建队列

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    /*

     系统默认的并发数是-1,所有任务全部并发执行

     */

    queue.maxConcurrentOperationCount = 3;//(产生4条线程)

    //2:封装操作

    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{

        [NSThread sleepForTimeInterval:1.0];

        NSLog(@"1------%@",[NSThread currentThread]);

    }];

    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{

        [NSThread sleepForTimeInterval:1.0];

        NSLog(@"2------%@",[NSThread currentThread]);

    }];

    NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{

        [NSThread sleepForTimeInterval:1.0];

        NSLog(@"3------%@",[NSThread currentThread]);

    }];

    NSBlockOperation *op4 = [NSBlockOperation blockOperationWithBlock:^{

        [NSThread sleepForTimeInterval:1.0];

        NSLog(@"4------%@",[NSThread currentThread]);

    }];

    NSBlockOperation *op5 = [NSBlockOperation blockOperationWithBlock:^{

        [NSThread sleepForTimeInterval:1.0];

        NSLog(@"5------%@",[NSThread currentThread]);

    }];

    NSBlockOperation *op6 = [NSBlockOperation blockOperationWithBlock:^{

        [NSThread sleepForTimeInterval:1.0];

        NSLog(@"6------%@",[NSThread currentThread]);

    }];

    //3:把操作添加到队列

    [queueaddOperation:op1];

    [queueaddOperation:op2];

    [queueaddOperation:op3];

    [queueaddOperation:op4];

    [queueaddOperation:op5];

    [queueaddOperation:op6];

    self.queue= queue;

}

2019-04-02 18:47:01.049897+0800 test666666[28710:3433110] 1------<NSThread: 0x6000022df780>{number = 5, name = (null)}

2019-04-02 18:47:01.049897+0800 test666666[28710:3433127] 3------<NSThread: 0x6000022df6c0>{number = 4, name = (null)}

2019-04-02 18:47:01.049921+0800 test666666[28710:3433109] 2------<NSThread: 0x6000022da6c0>{number = 3, name = (null)}

2019-04-02 18:47:02.053339+0800 test666666[28710:3433109] 6------<NSThread: 0x6000022da6c0>{number = 3, name = (null)}

2019-04-02 18:47:02.053461+0800 test666666[28710:3433125] 4------<NSThread: 0x6000022df7c0>{number = 6, name = (null)}

2019-04-02 18:47:02.053590+0800 test666666[28710:3433127] 5------<NSThread: 0x6000022df6c0>{number = 4, name = (null)}

第二、支持暂停、取消

self.queue.suspended 

[self.queue cancelAllOperations]

第三、支持KVO 监控线程状态

相关文章

网友评论

      本文标题:NSOperation 和 GCD 的区别

      本文链接:https://www.haomeiwen.com/subject/bdknbqtx.html