iOS:操作队列实现多线程NSOperation
NSOperation具体使用:直接继承NSObject
NSOperationQueuePriorityVeryLow = -8L,
NSOperationQueuePriorityLow = -4L,
NSOperationQueuePriorityNormal = 0,
NSOperationQueuePriorityHigh = 4,
NSOperationQueuePriorityVeryHigh = 8
};
@property (readonly, getter=isExecuting) BOOL executing; //线程是否在执行
@property (readonly, getter=isFinished) BOOL finished; //线程是否执行完毕
@property (readonly, getter=isConcurrent) BOOL concurrent; //线程是否并发执行
@property (readonly, getter=isAsynchronous) BOOL asynchronous; //是否线程异步,已经被线程同步覆盖
@property (readonly, getter=isReady) BOOL ready; //线程是否处于就绪状态
@property (readonly, copy) NSArray *dependencies; //线程依赖的数组
@property NSOperationQueuePriority queuePriority; //队列优先级
@property (copy) void (^completionBlock)(void); //block函数
@property double threadPriority; //线程优先级
@property NSQualityOfService qualityOfService; //服务质量
@property (copy) NSString *name; //线程名字
- (void)cancel;//取消线程
- (void)addDependency:(NSOperation *)op; //添加线程依赖(只有上一个线程一直执行,依赖的下一个线程才开始执行)
- (void)removeDependency:(NSOperation *)op; //移除线程依赖
- (void)waitUntilFinished //等待抢占资源的线程结束
================================================================================
属性:
@property (readonly, retain) NSInvocation *invocation; //线程的调用
@property (readonly, retain) id result;
方法:
//创建线程的实例方法,可以添加线程事件
- (instancetype)initWithTarget:(id)target selector:(SEL)sel object:(id)arg;
//创建线程的实例方法
- (instancetype)initWithInvocation:(NSInvocation *)inv ;
=================================================================
3、NSBlockOperation的详解:NSBlockOperation : NSOperation
属性:@property (readonly, copy) NSArray *executionBlocks; //执行block的线程队列数组
方法:
※创建线程的类方法,执行block函数
+ (instancetype)blockOperationWithBlock:(void (^)(void))block;
※添加执行线程对列block函数
- (void)addExecutionBlock:(void (^)(void))block;
==========================================================
4、NSOperationQueue队列的详解:NSOperationQueue : NSOperation
@property NSInteger maxConcurrentOperationCount; // 能并发执行的最大线程数量
@property (getter=isSuspended) BOOL suspended; //是否暂时线程
@property (copy) NSString *name ; //线程名字
@property NSQualityOfService qualityOfService; //服务质量
@property (assign /* actually retain */) dispatch_queue_t underlyingQueue;
方法:
※添加线程
- (void)addOperation:(NSOperation *)op;
※等待添加线程数组
- (void)addOperations:(NSArray *)ops waitUntilFinished:(BOOL)wait;
※添加线程并执行block函数的实例方法
- (void)addOperationWithBlock:(void (^)(void))block;
※取消所有的线程
- (void)cancelAllOperations;
※等待所有的线程执行完毕
- (void)waitUntilAllOperationsAreFinished;
※当前队列
+ (NSOperationQueue *)currentQueue;
※主队列
+ (NSOperationQueue *)mainQueue;
@interface ViewController ()
{
int tickets;
}
@property (weak, nonatomic) IBOutlet UITextView *textView;
2.设置票数和文本视图
//准备数据
tickets = ; //设置textView
self.textView.text = @"";
self.textView.layoutManager.allowsNonContiguousLayout = NO;
3.创建NSOperation实例(线程)
//创建NSOperation并加到队列
NSInvocationOperation *operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operationSellMethod:) object:@"售票线程-1"];
NSInvocationOperation *operation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operationSellMethod:) object:@"售票线程-2"];
4.将operation加入创建的队列中
//创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init]; //为操作之间添加依赖,只有被依赖的线程执行完,依赖的线程才能执行
//[operation1 addDependency:operation2]; //将opearion放入队列
[queue addOperation:operation1];
[queue addOperation:operation2];
5.更新UI的主线程队列
#pragma mark -更新UI
-(void)appendTextView:(NSString *)text
{
//1.获取原来的内容
NSMutableString *content = [[NSMutableString alloc]initWithString:self.textView.text];
NSRange range = NSMakeRange(content.length, ); //2.追加新的内容
[content appendString:[NSString stringWithFormat:@"\n%@",text]];
[self.textView setText:content]; //3.滚动视图
[self.textView scrollRangeToVisible:range];
}
6.执行对共享抢占资源操作的过程
#pragma mark -执行线程过程
-(void)operationSellMethod:(NSString*)name
{
while (YES)
{
//1.判断是否有票
if (tickets>)
{
//没有将共享抢占资源放到主队列中,仍然要关心数据同步的问题
@synchronized(self)
{
NSString *info = [NSString stringWithFormat:@"总的票数:%d,当前的线程:%@",tickets,name]; [[NSOperationQueue mainQueue]addOperationWithBlock:^{
[self appendTextView:info];
}]; //2.卖票
tickets--;
} //3.线程休眠
if([name isEqualToString:@"售票线程-1"])
{
[NSThread sleepForTimeInterval:0.3f];
}
else
{
[NSThread sleepForTimeInterval:0.2f];
}
}
else
{
//更新UI
NSString *info = [NSString stringWithFormat:@"票已经售完,当前的线程:%@",name];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self appendTextView:info];
}]; //退出线程
break;
}
}
}
方法二:采用NSOpeartion的子类NSBlockOperation创建多线程:
@interface ViewController ()
{
int tickets;
}
@property (weak, nonatomic) IBOutlet UITextView *textView;
2.设置票数和文本视图
//准备数据
tickets = 20; //设置textView
self.textView.text = @"";
self.textView.layoutManager.allowsNonContiguousLayout = NO;
3.创建队列和操作block线程
//创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init]; //设置并行的线程数量
//[queue setMaxConcurrentOperationCount:2]; //在队列中添加block的operation
[queue addOperationWithBlock:^{
[self operationSellMethod:@"售票线程-1"];
}]; [queue addOperationWithBlock:^{
[self operationSellMethod:@"售票线程-2"];
}]; NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
[self operationSellMethod:@"售票线程-3"];
}];
[queue addOperation:blockOperation];
4.更新UI的主线程队列
#pragma mark -更新UI
-(void)appendTextView:(NSString *)text
{
//1.获取原来的内容
NSMutableString *content = [[NSMutableString alloc]initWithString:self.textView.text];
NSRange range = NSMakeRange(content.length, ); //2.追加新的内容
[content appendString:[NSString stringWithFormat:@"\n%@",text]];
[self.textView setText:content]; //3.滚动视图
[self.textView scrollRangeToVisible:range];
}
5.执行对共享抢占资源操作的过程
#pragma mark -执行线程过程
#pragma mark -执行线程过程
-(void)operationSellMethod:(NSString*)name
{
while (YES)
{
//1.判断是否有票
if (tickets>)
{
//将共享抢占资源放入主队列,不需要再关心数据同步的问题
[[NSOperationQueue mainQueue]addOperationWithBlock:^{ NSString *info = [NSString stringWithFormat:@"总的票数:%d,当前的线程:%@",tickets,name]; [self appendTextView:info]; //2.卖票
tickets--;
}]; //3.线程休眠
if([name isEqualToString:@"售票线程-1"])
{
[NSThread sleepForTimeInterval:0.3f];
}
else
{
[NSThread sleepForTimeInterval:0.2f];
}
}
else
{
//更新UI
NSString *info = [NSString stringWithFormat:@"票已经售完,当前的线程:%@",name];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self appendTextView:info];
}]; //退出线程
break;
}
}
}
演示结果如下:

iOS:操作队列实现多线程NSOperation的更多相关文章
- iOS开发:Swift多线程NSOperation的使用
介绍: NSOperation是基于GCD实现,封装了一些更为简单实用的功能,因为GCD的线程生命周期是自动管理,所以NSOperation也是自动管理.NSOperation配合NSOperatio ...
- iOS边练边学--多线程NSOperation介绍,子类实现多线程的介绍(任务和队列),队列的取消、暂停(挂起)和恢复,操作依赖与线程间的通信
一.NSOperation NSOperation和NSOperationQueue实现多线程的具体步骤 先将需要执行的操作封装到一个NSOperation对象中 然后将NSOperation对象添加 ...
- iOS的三种多线程技术NSThread/NSOperation/GCD
1.iOS的三种多线程技术 1.NSThread 每个NSThread对象对应一个线程,量级较轻(真正的多线程) 2.以下两点是苹果专门开发的"并发"技术,使得程序员可以不再去关心 ...
- iOS之多线程NSOperation
目前在 iOS 和 OS X 中有两套先进的同步 API 可供我们使用:NSOperation 和 GCD .其中 GCD 是基于 C 的底层的 API ,而 NSOperation 则是 GCD 实 ...
- iOS 多线程 NSOperation、NSOperationQueue
1. NSOperation.NSOperationQueue 简介 NSOperation.NSOperationQueue 是苹果提供给我们的一套多线程解决方案.实际上 NSOperation.N ...
- IOS高级开发之多线程(四)NSOperation
1.什么是NSOperation,NSOperationQueue? NSOperation是一个抽象的基类,表示一个独立的计算单元,可以为子类提供有用且线程安全的建立状态,优先级,依赖和取消等操作. ...
- iOS中的多线程 NSOperation
在ios中,使用多线程有三种方式,分别是:NSThread.NSOperation和NSOperationQueue.GCD,在本节,主要讲解一下NSOperation的使用. NSOperation ...
- swift语言之多线程操作和操作队列(下)———坚持51天吃掉大象(写技术文章)
欢迎有兴趣的朋友,参与我的美女同事发起的活动<51天吃掉大象>,该美女真的很疯狂,希望和大家一起坚持51天做一件事情,我加入这个队伍,希望坚持51天每天写一篇技术文章.关注她的微信公众号: ...
- swift语言之多线程操作和操作队列(上)———坚持51天吃掉大象
欢迎有兴趣的朋友,参与我的美女同事发起的活动<51天吃掉大象>,该美女真的很疯狂,希望和大家一起坚持51天做一件事情,我加入这个队伍,希望坚持51天每天写一篇技术文章.关注她的微信公众号: ...
随机推荐
- eetcode 之String to Integer (atoi)(28)
字符串转为数字,细节题.要考虑空格.正负号,当转化的数字超过最大或最小是怎么办. int atoi(char *str) { int len = strlen(str); ; ; ; while (s ...
- hadoop 分布式环境安装
centos 多台机器免密登录 hadoop学习笔记(五)--全分布模式下SSH免密码登陆的实现 参考安装教程 Hadoop-2.7.4 集群快速搭建 启动hadoop cd /opt/soft/ha ...
- 机器学习方法(八):随机采样方法整理(MCMC、Gibbs Sampling等)
转载请注明出处:Bin的专栏,http://blog.csdn.net/xbinworld 本文是对参考资料中多篇关于sampling的内容进行总结+搬运,方便以后自己翻阅.其实参考资料中的资料写的比 ...
- <一>dubbo框架学前原理介绍
alibaba有好几个分布式框架,主要有:进行远程调用(类似于RMI的这种远程调用)的(dubbo.hsf),jms消息服务(napoli.notify),KV数据库(tair)等.这个框架/工具/产 ...
- javascript定义对象的方式
javascript定义对象的方式(javascript中没有类,只有对象)1)基于已有对象扩充属性和方法(弊端:每次创建都与要重新定义属性方法) var object = new Object(); ...
- MFC宏常识
1.宏就是用宏定义指令#define定义一个标识符,用它来表示一个字符串或一段源代码. MFC宏作为MFC类库的一个组成部分在MFC应用程序中经常出现. MFC宏在路径 ".../Micro ...
- 【面试题】2018年最全Java面试通关秘籍汇总集!
[面试题]2018年最全Java面试通关秘籍汇总集!(转载于互联网) 前几天在交流群里有些小伙伴问面试相关的试题,当时给出了一些问题,苦于打字太累就没写下去了,但觉得这是一个很不负责任的表现,于是 ...
- [putty] ubuntu 通过配置文件设置字体
创建了一个session之后,就能在 ~/.putty/sessions/ 文件夹下看到session的配置文件了 $ vim ~/.putty/sessions/session-name 搜索Fon ...
- HDU 5514.Frogs-欧拉函数 or 容斥原理
Frogs Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submi ...
- vue中的锚链接跳转问题
在vue中的锚链接和普通的html不同,关于vue中的锚链接可以参考vue 中的 scrollBehavior 滚动行为. 在router.js中 //创建 router 实例 const rout ...