通过设置NSOperationQueue的最大并发数,决定同一时间执行的操作数目
@property NSInteger maxConcurrentOperationCount;
示例代码:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController{
NSOperationQueue *_queue; // 全局队列
}
- (void)viewDidLoad {
[super viewDidLoad];
// 实例化队列对象
_queue = [[NSOperationQueue alloc] init];
// 设置最大并发数 (同一时间执行的操作数目)
_queue.maxConcurrentOperationCount = 3;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
// 通过for循环模拟20个操作
for (int i = 0; i < 20; i ++) {
// 异步执行操作
[_queue addOperationWithBlock:^{
[NSThread sleepForTimeInterval:3];
NSLog(@"%d-->%@",i,[NSThread currentThread]);
}];
}
}
@end
当系统从队列中取出操作对象时,会先根据线程池中查找是否有可用线程
如果有,直接使用,如果没有,就开辟新线程
因为线程也会占据内存,开启销毁也会浪费系统资源,通过线程池的重用机制以及设置合理的最大并发数,可以在一定程度上提升性能
- 注意:
设置最大并发数,并不代表开启的线程数,而是开启的最小线程数(抛去主线程)