NSOpseration是抽象基类,所以要用子类实现它的方法。(内部使用gcd实现)
1.一个NSOperation 就代表一个任务,任务的代码分装在block里或者函数里。 OC提供子类: NSInvocztionOperation:任务是一个函数,比较长 NSBlockOperation:任务是一个block,比较短常用方法demo:(有关线程执行方式,队列类型看)
1.1NSBlockOperation:
- (void) testBlockOperation2{ //情况1. NSBlockOperation *operationA = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"startA:%@", [NSThread currentThread]); }]; [operationA start]; NSBlockOperation *operationB = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"startB:%@", [NSThread currentThread]); }]; [operationB start]; NSBlockOperation *operationC = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"startC:%@", [NSThread currentThread]); }]; [operationC start]; //情况2. NSBlockOperation *operation = [[ NSBlockOperation alloc] init]; [operation addExecutionBlock:^{ NSLog(@"start1:%@", [NSThread currentThread]); }]; [operation addExecutionBlock:^{ NSLog(@"start2:%@", [NSThread currentThread]); }]; [operation addExecutionBlock:^{ NSLog(@"start3:%@", [NSThread currentThread]); }]; [operation start];}
可以看到任务配置好以后,直接执行时同步的。而把任务block放到一起的时候是异步的。
- (void) testBlockOperation{ //情况3. NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"start1:%@", [NSThread currentThread]); }]; NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"start2:%@", [NSThread currentThread]); }]; NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"start3:%@", [NSThread currentThread]); }]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperations:@[operation3, operation2, operation1] waitUntilFinished:NO];}
放到全局队列里也是异步的(并发),如果放到主队列([NSOperationQueue mainQueue])里,那么是同步的。
1.2NSInvocztionOperation:使用它和NSBlockOperation是一样的。都是NSOperation的子类……
- (void) testOperationInvocation{ NSOperationQueue *queue = [[NSOperationQueue alloc] init]; NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationFirst:) object:@"start"]; [operation1 start]; NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationFirst:) object:@"newQ"]; [queue addOperation:operation2];}- (void) operationFirst:(NSString *) who{ NSLog(@"\n%@, %s, %@", who, __func__, [NSThread currentThread]);}
2.任务间依赖关系:也是用来实现异步线程间通信的一种约定
- (void) operationDependency{ NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"thread 1"); }]; [operation1 setCompletionBlock:^{ NSLog(@"finish thread1"); }]; NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"thread 2"); }]; NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"thread 3"); }]; [operation1 addDependency:operation2]; [operation2 addDependency:operation3]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperation:operation1]; [queue addOperation:operation2]; [queue addOperation:operation3];}
依据依赖顺序执行