#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong)NSOperationQueue * queue;
@end
@implementation ViewController
-(NSOperationQueue *)queue
{
if(!_queue)
{
//初始化队列
_queue=[[NSOperationQueue alloc]init];
//设置最大并发数,不是说代表我只开两个线程,因为线程之间是相互切换的,万一你两个线程中的一个线程进入了就绪状态,那我肯定还需要一个线程去继续完成任务。
_queue.maxConcurrentOperationCount=2;
}
return _queue;
}
- (void)viewDidLoad {
[super viewDidLoad];
for(int i=0;i<10;i++)
{
[self.queue addOperationWithBlock:^{
NSLog(@"%d %@",i,[NSThread currentThread]);
}];
}
}
此处开启了三个线程
//输出队列的操作数
NSLog(@"%zd",self.queue.operationCount);
//继续操作
self.queue.suspended=NO;
//暂停操作,当前正在执行的操作会执行完毕,后续的操作会暂停
self.queue.suspended=YES;
//取消所有操作,会把操作从队列中全部移除掉
[self.queue cancelAllOperations];