一:NSOperation 两个子类+重写main方法
- NSInvocationOperation
- NSBlockOperation 有个类方法 BlockOprationWith:
- 还有就是自己个子类重写main方法,把任务写在main方法里面
二:NSOperationQueue 线程管理器
- 类方法 mainQueue
- 类方法 currentQueue
- alloc init 新Queue
三:使用代码:(ARC环境)
#pragma mark NSOperationQueue - (void)doBtnFoure { //一:主线程测试; //NSOperationQueue *mainQueue = [NSOperationQueue mainQueue]; //主线种之中添加任务;卡UI //测试一; // [mainQueue addOperationWithBlock:^{ // [self doOperation:@"NSOperationQueue MainQueue"]; // }]; //测试2; // [mainQueue addOperation:[NSBlockOperation blockOperationWithBlock:^{ // [self doOperation:@"MainQueue add BlockOperation"]; // }]]; //二:创建Quene,其他线程处理;不卡UI; 默认并行,异步执行; NSOperationQueue *myQueue = [[NSOperationQueue alloc]init]; myQueue.maxConcurrentOperationCount = 2; //设置并行操作线程的最大个数; [myQueue addOperationWithBlock:^{ [self doOperation:@"MyQueue "]; }]; [myQueue addOperation:[NSBlockOperation blockOperationWithBlock:^{ [self doOperation:@"MyQueue NSBlockOperation"]; }]]; NSInvocationOperation *invoOp = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(doOperation:) object:@"MyQueue NSInvocationOp"]; [myQueue addOperation:invoOp]; } #pragma mark 自定的 MyOperation - (void)doBtnThree { // 串行执行任务,卡UI 在 当前线程执行; MyOperation *myOperation = [[MyOperation alloc]init]; [myOperation start]; MyOperation *op2 = [[MyOperation alloc]init]; [op2 start]; } #pragma mark 只有将operation放到一个NSOperationQueue中,才会异步执行操作 // - (void)doBtnTwo { //卡UI,在当前线程之中执行;同步,串行执行多个NSBlockOp,并行执行NSOp里面的 ExecuBlock; //每个ExecuBlock都是一个新的线程; NSBlockOperation *blockOp = [[NSBlockOperation alloc]init]; [blockOp addExecutionBlock:^{ [self doOperation:@"NSBlockOperation1 1111"]; }]; [blockOp addExecutionBlock:^{ [self doOperation:@"NSBlockOperation1 2222"]; }]; [blockOp start]; /* 线程执行完的操作; blockOp.completionBlock = ^(){ NSLog(@"执行完成"); }; */ NSBlockOperation *blockOp2 = [[NSBlockOperation alloc]init]; [blockOp2 addExecutionBlock:^{ [self doOperation:@"NSBlockOperation2 1111"]; }]; [blockOp2 addExecutionBlock:^{ [self doOperation:@"NSBlockOperation2 2222"]; }]; [blockOp2 start]; } - (void)doBtnOne { //在当前线程中执行,卡UI ;同步,串行; NSInvocationOperation *oper1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(doOperation:) object:@"NSINvocationOperation 111"]; NSInvocationOperation *oper2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(doOperation:) object:@"NSINvocationOperation 222"]; [oper1 start]; [oper2 start]; } //任务测试 - (void)doOperation:(NSString *)aStr { for (int i = 0; i < 5000; i ++) { NSLog(@"%@ --> %d",aStr,i); } }