1.NSOperation–最大并发数
什么是并发数
同时执行的任务数,比如同时开3个线程执行3个任务,并发数就是3
最大并发数的相关方法
-(NSInteger)maxConcurrentOperationCount;
-(void)setMaxConcurrentOperationCount:(NSInteger)cnt;
执行的过程
1.把操作添加到队列self.queue addOperationWithBlock
2.去线程池取空闲的线程,如果没有就创建线程
3.把操作交给从线程池中取出的线程执行
4.执行完成后,把线程再放回线程池中
5.重复2、3、4直到所有的操作都执行
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong)NSOperationQueue* queue;
@end
@implementation ViewController
//懒加载
-(NSOperationQueue*)queue{
if(_queue==nil){
_queue=[[NSOperationQueue alloc]init];
//设置最大并发数
_queue.maxConcurrentOperationCount=2;
}
return _queue;
}
- (void)viewDidLoad {
[super viewDidLoad];
for (int i=0; i<20; i++) {
[self.queue addOperationWithBlock:^{
[NSThread sleepForTimeInterval:1];
NSLog(@"%d %@",i,[NSThread currentThread]);
}];
}
}
@end
2020-08-07 10:44:10.166405+0800 IOS113[7379:88246] 0 <NSThread: 0x6000034ecd40>{number = 4, name = (null)}
2020-08-07 10:44:10.166403+0800 IOS113[7379:88244] 1 <NSThread: 0x6000034ecac0>{number = 5, name = (null)}
2020-08-07 10:44:11.170643+0800 IOS113[7379:88244] 3 <NSThread: 0x6000034ecac0>{number = 5, name = (null)}
2020-08-07 10:44:11.170646+0800 IOS113[7379:88247] 2 <NSThread: 0x6000034efb80>{number = 7, name = (null)}
以上开了4,5,7三个线程,比设定的值要多1,这是oc相应机制引起的,不是错误
2.队列的暂停,取消,恢复
取消队列的所有操作
-(void)cancelAllOperation
也可以调用NSOperation的-(void)cancel方法取消单个操作
暂停和恢复队列
-(void)setSuspended:(BOOl)b;//YES代表暂停队列,NO表示恢复队列
-(BOOL)isSuspended;
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong)NSOperationQueue* queue;
- (IBAction)cancelQueue:(id)sender;
- (IBAction)pauseQueue:(id)sender;
- (IBAction)continueQueue:(id)sender;
@end
@implementation ViewController
//懒加载
-(NSOperationQueue*)queue{
if(_queue==nil){
_queue=[[NSOperationQueue alloc]init];
//设置最大并发数
_queue.maxConcurrentOperationCount=2;
}
return _queue;
}
- (void)viewDidLoad {
[super viewDidLoad];
for (int i=0; i<20; i++) {
[self.queue addOperationWithBlock:^{
[NSThread sleepForTimeInterval:1];
NSLog(@"%d %@",i,[NSThread currentThread]);
}];
}
}
//继续队列操作
- (IBAction)continueQueue:(id)sender {
[self.queue setSuspended:NO];
NSLog(@"继续");
}
//暂停队列操作
- (IBAction)pauseQueue:(id)sender {
[self.queue setSuspended:YES];
NSLog(@"暂停");//暂停后续操作,因此还会继续执行一会
}
//取消队列操作
- (IBAction)cancelQueue:(id)sender {
[self.queue cancelAllOperations];
NSLog(@"取消");
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//队列中的操作数
NSLog(@"%zd",self.queue.operationCount);
}
@end
3.摇奖机案例
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *first;
@property (weak, nonatomic) IBOutlet UILabel *second;
@property (weak, nonatomic) IBOutlet UILabel *third;
@property (weak, nonatomic) IBOutlet UIButton