给任务添加依赖 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)}
网友评论