// // ViewController.m // OperationTest0108 // // Created by LongMa on 2020/1/8. // #import "ViewController.h" #import <AFNetworking/AFNetworking.h> @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self testQueue]; } - (void)testQueue{ NSOperationQueue *lQ = [[NSOperationQueue alloc] init]; //任務最大併發數,與是否開啓子線程無關。 // lQ.maxConcurrentOperationCount = 1; NSBlockOperation *lOp0 = [NSBlockOperation blockOperationWithBlock:^{ AFHTTPSessionManager *lMng = [AFHTTPSessionManager manager]; [lMng POST:@"https://www.baidu.com" parameters:@{ @"mapId" : @"1" } progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"0 suc"); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"0 error"); }]; NSLog(@"0 %@", [NSThread currentThread]); }]; NSBlockOperation *lOp1 = [NSBlockOperation blockOperationWithBlock:^{ AFHTTPSessionManager *lMng = [AFHTTPSessionManager manager]; [lMng POST:@"https://www.baidu.com" parameters:@{ @"mapId" : @"1" } progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"1 suc"); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"1 error"); }]; NSLog(@"1 %@", [NSThread currentThread]); }]; NSBlockOperation *lOp2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"2 %@", [NSThread currentThread]); }]; [lOp0 addDependency:lOp1]; NSLog(@"before add op"); [lQ addOperations:@[lOp0] waitUntilFinished:NO]; [lQ addOperations:@[lOp1] waitUntilFinished:NO]; [lQ addOperations:@[lOp2] waitUntilFinished:NO]; } @end
執行結果網絡
2020-01-08 18:02:31.378260+0800 OperationTest0108[1583:527022] before add op 2020-01-08 18:02:31.378635+0800 OperationTest0108[1583:527045] 2 <NSThread: 0x283db43c0>{number = 4, name = (null)} 2020-01-08 18:02:31.379722+0800 OperationTest0108[1583:527047] 1 <NSThread: 0x283db4240>{number = 5, name = (null)} 2020-01-08 18:02:31.380265+0800 OperationTest0108[1583:527047] 0 <NSThread: 0x283db4240>{number = 5, name = (null)} 2020-01-08 18:02:31.915236+0800 OperationTest0108[1583:527022] 0 error 2020-01-08 18:02:31.921841+0800 OperationTest0108[1583:527022] 1 error
由上面log可知:任務結束斷定以發起請求爲準!數據返回是異步的,不受依賴關係影響!併發
當把上面代碼異步
[lQ addOperations:@[lOp0] waitUntilFinished:NO];
改成線程
[lQ addOperations:@[lOp0] waitUntilFinished:YES];
時,
log以下,沒有正常執行操做:3d
2020-01-08 18:03:55.308276+0800 OperationTest0108[1587:527738] before add op
分析:
waitUntilFinished方法定義爲:
If YES, the current thread is blocked until all of the specified operations finish executing. If NO, the operations are added to the queue and control returns immediately to the caller.
當爲YES時,當前線程被阻塞,直到被添加的操做執行完畢。上面代碼使線程依賴於lOp0執行完畢,而lOp0的執行依賴於lOp1執行完畢。因爲lOp1比lOp0加入隊列更晚。當上面代碼被執行時,線程在等lOp0執行完畢,而此時lOp1還沒被加入隊列中,即lOp1還沒開始執行,因此線程一直處於阻塞狀態!固然,合理利用waitUntilFinished方法,也能實現想要的特殊效果。code