NSOperationQueue

NSOperationQueue

NSOperationQueue 队列 包含了 主队列 和 非主队列

    //创建主队列
    NSOperationQueue * mainQueue = [NSOperationQueue mainQueue];
    //创建非主队列
    NSOperationQueue * otherQueue = [[NSOperationQueue alloc] init];
 NSBlockOperation * opOne = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"线程 ------%@",[NSThread currentThread]);
        NSLog(@"一号开始执行");
        
    }];
    [opOne addExecutionBlock:^{
        NSLog(@"线程1 ------%@",[NSThread currentThread]);
        NSLog(@"二号开始执行");
    }];
    
    [opOne addExecutionBlock:^{
        NSLog(@"线程3 ------%@",[NSThread currentThread]);
        NSLog(@"三号开始执行");
    }];
    
    //创建非主队列
    NSOperationQueue * otherQueue = [[NSOperationQueue alloc] init];
    
    [otherQueue addOperation:opOne];
线程1 ------<NSThread: 0x600000318fc0>{number = 4, name = (null)}
线程 ------<NSThread: 0x60000032f2c0>{number = 3, name = (null)}
线程3 ------<NSThread: 0x60000032f240>{number = 5, name = (null)}
三号开始执行
二号开始执行
一号开始执行

可以看出任务开始并发执行

任务依赖
NSInvocationOperation * op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocation) object:nil];

 NSBlockOperation * opOne = [NSBlockOperation blockOperationWithBlock:^{
        sleep(5);
        NSLog(@"1结束了");
        
    }];
   
NSBlockOperation * opTwo = [NSBlockOperation blockOperationWithBlock:^{
        sleep(5);
        NSLog(@"2结束了");
        
    }];

NSOperationQueue * otherQueue = [[NSOperationQueue alloc] init];
    otherQueue.maxConcurrentOperationCount = 1; //设置1 串行执行  大于1 并发执行   默认-1 不限制
    op.queuePriority = NSOperationQueuePriorityVeryHigh;
    [op addDependency:opOne];
    [opTwo addDependency:op];
    [otherQueue addOperation:opOne];
    [otherQueue addOperation:op];
    [otherQueue addOperation: opTwo];

-(void)invocation {
    NSLog(@"线程4 ------%@",[NSThread currentThread]);
    NSLog(@"任务结束了");
}
1结束了
线程4 ------<NSThread: 0x60000299b0c0>{number = 3, name = (null)}
任务结束了
2结束了
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容