已阅读5页,还剩4页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
iOS多线程编程之NSThread的使用分类:iOS开发进阶2012-09-23 23:3739189人阅读评论(18)收藏举报目录(?)+1、简介:1.1 iOS有三种多线程编程的技术,分别是:1.、NSThread2、Cocoa NSOperation(iOS多线程编程之NSOperation和NSOperationQueue的使用)3、GCD全称:Grand Central Dispatch(iOS多线程编程之Grand Central Dispatch(GCD)介绍和使用)这三种编程方式从上到下,抽象度层次是从低到高的,抽象度越高的使用越简单,也是Apple最推荐使用的。这篇我们主要介绍和使用NSThread,后面会继续2、3 的讲解和使用。1.2 三种方式的有缺点介绍:NSThread:优点:NSThread 比其他两个轻量级缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销NSThread实现的技术有下面三种:TechnologyDescriptionCocoa threadsCocoa implements threads using theNSThreadclass. Cocoa also provides methods onNSObjectfor spawning new threads and executing code on already-running threads. For more information, see“Using NSThread”and“Using NSObject to Spawn a Thread.”POSIX threadsPOSIX threads provide a C-based interface for creating threads. If you are not writing a Cocoa application, this is the best choice for creating threads. The POSIX interface is relatively simple to use and offers ample flexibility for configuring your threads. For more information, see“Using POSIX Threads”Multiprocessing ServicesMultiprocessing Services is a legacy C-based interface used by applications transitioning from older versions of Mac OS. This technology is available in OS X only and should be avoided for any new development. Instead, you should use theNSThreadclass or POSIX threads. If you need more information on this technology, seeMultiprocessing Services Programming Guide.一般使用cocoa thread 技术。Cocoa operation优点:不需要关心线程管理,数据同步的事情,可以把精力放在自己需要执行的操作上。Cocoa operation 相关的类是NSOperation ,NSOperationQueue。NSOperation是个抽象类,使用它必须用它的子类,可以实现它或者使用它定义好的两个子类:NSInvocationOperation 和 NSBlockOperation。创建NSOperation子类的对象,把对象添加到NSOperationQueue队列里执行。GCDGrand Central Dispatch (GCD)是Apple开发的一个多核编程的解决方法。在iOS4.0开始之后才能使用。GCD是一个替代诸如NSThread, NSOperationQueue, NSInvocationOperation等技术的很高效和强大的技术。现在的iOS系统都升级到6了,所以不用担心该技术不能使用。介绍完这三种多线程编程方式,我们这篇先介绍NSThread的使用。2、NSThread的使用2.1 NSThread 有两种直接创建方式:- (id)initWithTarget:(id)targetselector:(SEL)selectorobject:(id)argument+ (void)detachNewThreadSelector:(SEL)aSelectortoTarget:(id)aTargetwithObject:(id)anArgument第一个是实例方法,第二个是类方法cppview plaincopy1. 1、NSThreaddetachNewThreadSelector:selector(doSomething:)toTarget:selfwithObject:nil;2. 2、NSThread*myThread=NSThreadallocinitWithTarget:self3. selector:selector(doSomething:)4. object:nil;5. myThreadstart;2.2参数的意义:selector :线程执行的方法,这个selector只能有一个参数,而且不能有返回值。target :selector消息发送的对象argument:传输给target的唯一参数,也可以是nil第一种方式会直接创建线程并且开始运行线程,第二种方式是先创建线程对象,然后再运行线程操作,在运行线程操作前可以设置线程的优先级等线程信息2.3 PS:不显式创建线程的方法:用NSObject的类方法 performSelectorInBackground:withObject: 创建一个线程:Obj performSelectorInBackground:selector(doSomething) withObject:nil;2.4 下载图片的例子:2.4.1 新建singeView app新建项目,并在xib文件上放置一个imageView控件。按住control键拖到viewController.h文件中创建imageView IBOutletViewController.m中实现:cppview plaincopy1. /2. /ViewController.m3. /NSThreadDemo4. /5. /Createdbyrongfzhon12-9-23.6. /Copyright(c)2012年rongfzh.Allrightsreserved.7. /8. 9. #importViewController.h10. #definekURL/2/C/D/1_totogo2010.jpg11. interfaceViewController()12. 13. end14. 15. implementationViewController16. 17. -(void)downloadImage:(NSString*)url18. NSData*data=NSDataallocinitWithContentsOfURL:NSURLURLWithString:url;19. UIImage*image=UIImageallocinitWithData:data;20. if(image=nil)21. 22. else23. selfperformSelectorOnMainThread:selector(updateUI:)withObject:imagewaitUntilDone:YES;24. 25. 26. 27. -(void)updateUI:(UIImage*)image28. self.imageView.image=image;29. 30. 31. 32. -(void)viewDidLoad33. 34. superviewDidLoad;35. 36. /NSThreaddetachNewThreadSelector:selector(downloadImage:)toTarget:selfwithObject:kURL;37. NSThread*thread=NSThreadallocinitWithTarget:selfselector:selector(downloadImage:)object:kURL;38. threadstart;39. 40. 41. -(void)didReceiveMemoryWarning42. 43. superdidReceiveMemoryWarning;44. /Disposeofanyresourcesthatcanberecreated.45. 46. 47. end2.4.2线程间通讯线程下载完图片后怎么通知主线程更新界面呢?selfperformSelectorOnMainThread:selector(updateUI:)withObject:imagewaitUntilDone:YES;performSelectorOnMainThread是NSObject的方法,除了可以更新主线程的数据外,还可以更新其他线程的比如:用:performSelector:onThread:withObject:waitUntilDone:运行下载图片:图片下载下来了。2.3 线程同步我们演示一个经典的卖票的例子来讲NSThread的线程同步:.hcppview plaincopy1. #import2. 3. classViewController;4. 5. interfaceAppDelegate:UIResponder6. 7. inttickets;8. intcount;9. NSThread*ticketsThreadone;10. NSThread*ticketsThreadtwo;11. NSCondition*ticketsCondition;12. NSLock*theLock;13. 14. property(strong,nonatomic)UIWindow*window;15. 16. property(strong,nonatomic)ViewController*viewController;17. 18. endcppview plaincopy1. -(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions2. 3. 4. tickets=100;5. count=0;6. theLock=NSLockallocinit;7. /锁对象8. ticketsCondition=NSConditionallocinit;9. ticketsThreadone=NSThreadallocinitWithTarget:selfselector:selector(run)object:nil;10. ticketsThreadonesetName:Thread-1;11. ticketsThreadonestart;12. 13. 14. ticketsThreadtwo=NSThreadallocinitWithTarget:selfselector:selector(run)object:nil;15. ticketsThreadtwosetName:Thread-2;16. ticketsThreadtwostart;17. 18. self.window=UIWindowallocinitWithFrame:UIScreenmainScreenbounds;19. /Overridepointforcustomizationafterapplicationlaunch.20. self.viewController=ViewControllerallocinitWithNibName:ViewControllerbundle:nil;21. self.window.rootViewController=self.viewController;22. self.windowmakeKeyAndVisible;23. returnYES;24. 25. 26. -(void)run27. while(TRUE)28. /上锁29. /ticketsConditionlock;30. theLocklock;31. if(tickets=0)32. NSThreadsleepForTimeInterval:0.09;33. count=100-tickets;34. NSLog(当前票数是:%d,售出:%d,线程名:%,tickets,count,NSThreadcurrentThreadname);35. tickets-;36. else37. break;38. 39. theLockunlock;40. /ticketsConditionunlock;41. 42. 如果没有线程同步的lock,卖票数可能是-1.加上lock之后线程同步保证了数据的正确性。上面例子我使用了两种锁,一种NSCondition ,一种是:NSLock。 NSCondition我已经注释了。线程的顺序执行他们都可以通过 ticketsConditionsignal; 发送信号的方式,在一个线程唤醒另外一个线程的等待。比如:cppview plaincopy1. #importAppDelegate.h2. 3. #importViewController.h4. 5. implementationAppDelegate6. 7. -(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions8. 9. 10. tickets=100;11. count=0;12. theLock=NSLockallocinit;13. /锁对象14. ticketsCondition=NSConditionallocinit;15. ticketsThreadone=NSThreadallocinitWithTarget:selfselector:selector(run)object:nil;16. ticketsThreadonesetName:Thread-1;17. ticketsThreadonestart;18. 19. ticketsThreadtwo=NSThreadallocinitWithTarget:selfselector:selector(run)object:nil;20. ticketsThreadtwosetName:Thread-2;21. ticketsThreadtwostart;22. 23. NSThread*ticketsThreadthree=NSThreadallocinitWithTarget:selfselector:selector(run3)object:nil;24. ticketsThreadthreesetName:Thread-3;25. ticketsThreadthreestart;26. self.window=UIWindowallocinitWithFrame:UIScreenmainScreenbounds;27. /Overridepointforcustomizationafterapplicationlaunch.28. self.viewController=ViewControllerallocinitWithNibName:ViewControllerbundle:nil;29. self.window.rootViewController=self.viewController;30. self.windowmakeKeyAndVisible;31. returnYES;32. 33. 34. -(void)run335. while(YES)36. ticketsConditionlock;37. NSThreadsleepForTimeInterval:3;38. ticketsConditionsignal;39. ticketsConditionunlock;40. 41. 42. 43. -(void)
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 防疫园区进出管理制度(3篇)
- 供电的应急预案(3篇)
- 柳树移植施工方案(3篇)
- 物业管理费收缴流程与法律法规
- 中学生常见违纪行为与辅导策略
- 三方股权投资协议解析
- 小班家长会组织方案与发言稿
- 高中语文文言文虚词实词详解资料
- 员工职业健康体检方案制定与实施
- 建筑施工劳务用工合同大全
- 大学英语学术阅读知到章节答案智慧树2023年南京大学
- EBZ掘进机电气原理图三一重工
- 汉字英雄试题库
- 两篇古典英文版成语故事狐假虎威
- GB/T 6109.11-1990漆包圆绕组线第11部分:200级聚酯亚胺/聚酰胺酰亚胺复合漆包铜圆线
- GB/T 29475-2012移动实验室设计原则及基本要求
- 职业性格测验量表
- 甲A写字楼物业管理手册
- 建设工程造价咨询成果文件质量标准课件
- 众辰变频器说明书3400
- 《做一个负责任的人》主题班会课件
评论
0/150
提交评论