创建方法
//方法一:操作队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
//最大操作数:设为1的话,从前往后执行;设置为其他,并发执行
queue.maxConcurrentOperationCount = 1;
//被挂起(暂停)目的是:加载了所有的任务才执行队列
queue.suspended = YES;
[queue addOperationWithBlock:^{
NSLog(@"1--是否为主线程:%d",[[NSThread currentThread]isMainThread]);
NSLog(@"1--优先级:%f",[NSThread threadPriority]);
}];
//方法二:NSOperation(操作任务)的子类: NSInvocationOperation
NSInvocationOperation *invocationOp = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(invocationAction:) object:@"invocation"];
//添加到队列中
[queue addOperation:invocationOp];
//监听invocationOp任务是否完成,完成后调用此方法
invocationOp.completionBlock = ^(){
NSLog(@"2--invocationOp任务完成");
};
//NSInvocationOperation线程实现的方法
- (void)invocationAction:(NSString *)t{
NSLog(@"2--%@",t);
NSLog(@"2--是否为主线程:%d",[[NSThread currentThread]isMainThread]);
NSLog(@"2--优先级:%f",[NSThread threadPriority]);
}
//方法三:NSOperation(操作任务)的子类:NSBlockOperation可以并发执行一个或多个任务
NSBlockOperation *blockOp = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"3---是否为主线程:%d",[[NSThread currentThread]isMainThread]);
NSLog(@"3--优先级:%f",[NSThread threadPriority]);
}];
[blockOp addExecutionBlock:^{
NSLog(@"3--再执行一个任务");
}];
[blockOp addExecutionBlock:^{
NSLog(@"3--又执行一个任务");
}];
//该方法监听blockOp任务是否完成,完成后调用此方法
blockOp.completionBlock = ^(){
NSLog(@"3--blocp执行完成");
};
[queue addOperation:blockOp];
//添加依赖关系:意思是先执行blockOp,再执行invocationOp
[invocationOp addDependency:blockOp];
//方法四:自定义opration
CustomOpration *customOpration = [[CustomOpration alloc]init];
//设置优先级:来改变任务处理的顺序,这里设置为最高等级,最先处理
customOpration.queuePriority = NSOperationQueuePriorityVeryHigh;
[queue addOperation:customOpration];
//自定义CustomOpration.m 文件中的代码
#import "CustomOpration.h"
@implementation CustomOpration
- (void)main{
for (int i=0; i<5; i++) {
NSLog(@"4------%d",i);
}
}
取消方法
//取消某个任务 ,这里的cancelOp已经设为全局,目的为了后面方便使用
cancelOp = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(cancelOpAction) object:nil];
[self performSelector:@selector(cancelSingle:) withObject:cancelOp afterDelay:1];
[queue addOperation:cancelOp];
//取消所有队列,不过只能取消没有执行的队列
//[queue cancelAllOperations];
//取消操作队列暂停
queue.suspended = NO;
}
//取消的方法
- (void)cancelSingle:(NSInvocationOperation *)op{
[op cancel];
}
//cancelOp线程实现的方法
- (void)cancelOpAction{
//休眠2秒
[NSThread sleepForTimeInterval:2];
if ([cancelOp isCancelled]) {
//如果确定已经取消,打印下面的语句,其他语句不打印
NSLog(@"已经取消了,不会执行以下语句");
}
NSLog(@"我能执行吗");
}
网友评论