美文网首页
iOS多线程之NSOperation与NSOperationQu

iOS多线程之NSOperation与NSOperationQu

作者: iOS扫地僧 | 来源:发表于2018-03-02 17:13 被阅读0次
    给任务添加依赖 addDependency:
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        NSOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
            sleep(5);
            NSLog(@"任务 1%@",[NSThread currentThread]);
            
        }];
        NSOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
            sleep(6);
            NSLog(@"任务 2%@",[NSThread currentThread]);
            
        }];
        NSOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"任务 3%@",[NSThread currentThread]);
            
        }];
        //让任务3在任务1完成后再执行
        [op3 addDependency:op1];
        //让任务1在任务2完成后再执行
        [op1 addDependency:op2];
        [queue addOperations:@[op1, op2, op3] waitUntilFinished:YES];
    

    运行结果为:

    2018-03-02 17:11:40.932543+0800 平常测试[8147:1428152] 任务 2<NSThread: 0x600000264f80>{number = 3, name = (null)}
    2018-03-02 17:11:45.937063+0800 平常测试[8147:1428159] 任务 1<NSThread: 0x60000026ea40>{number = 4, name = (null)}
    2018-03-02 17:11:45.937501+0800 平常测试[8147:1428152] 任务 3<NSThread: 0x600000264f80>{number = 3, name = (null)}
    

    相关文章

      网友评论

          本文标题:iOS多线程之NSOperation与NSOperationQu

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