子线程同时发起多个异步操作,需要得到上一个操作的回调,再执行下一个操作。
所有操作暂时全部放入数组,通过对数组操作,使队列每次只放一个操作任务,依次执行完毕。直到数组为空,所有操作都完成。这么做,可解决token短时间过期,经常更换,app同时发起多个请求被强制下线的问题。
//
// ViewController.m
// lockDemo
//
// Created by huant on 2018/12/3.
// Copyright © 2018年 huant. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) NSMutableArray * opens;
@property (nonatomic, strong) NSOperationQueue * queue;
@end
@implementation ViewController
static int a = 1000;
- (void)viewDidLoad {
[super viewDidLoad];
self.opens = [[NSMutableArray alloc] init];
NSBlockOperation * block = [NSBlockOperation blockOperationWithBlock:^{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"================");
[self removeOp];
});
for (int i = 0; i<100; i++) {
[self print:@"111"];
}
}];
NSBlockOperation * block1 = [NSBlockOperation blockOperationWithBlock:^{
for (int i = 0; i<100; i++) {
[self print:@"222222222"];
}
[self removeOp];
}];
NSBlockOperation * block2 = [NSBlockOperation blockOperationWithBlock:^{
for (int i = 0; i<100; i++) {
[self print:@"33333333333333"];
}
[self removeOp];
}];
[self.opens addObject:block];
[self.opens addObject:block1];
[self.opens addObject:block2];
[self.queue addOperation:self.opens.firstObject];
}
- (void)removeOp{
if (_opens.count) {
[self.opens removeObjectAtIndex:0];
}
if (self.opens.count) {
[self.queue addOperation:self.opens.firstObject];
}
}
- (NSOperationQueue *)queue{
if (!_queue) {
_queue = [NSOperationQueue new];
}
return _queue;
}
- (void)print:(NSString *)str{
@synchronized (self) {
NSLog(@"%@", str);
// NSLog(@"%@", [NSThread currentThread]);
--a;
NSLog(@"%d", a);
}
}
@end