不管是iphone 中还是其他的操作系统,多线程在各种编程语言中都是难点,很多语言中实现起来很麻烦,objective-c虽然源于c,但其多线程编程却相当简单,可以与java 相媲美。多线程编程是防止主线程堵塞,增加运行效率等等的最佳方法。而原始的多线程方法存在很多的毛病,包括线程锁死等。
一、线程创建与启动
线程创建主要有二种方式:
- (id)init;//designatedinitializer
- (id)initWithTarget:(id)targetselector:
- (SEL)selectorobject:(id)argument;
当然,还有一种比较特殊,就是使用所谓的convenient method,这个方法可以直接生成一个线程并启动它,而且无需为线程的清理负责。这个方法的接口是:
- (void)detachNewThreadSelector:
- (SEL)aSelectortoTarget:
- (id)aTargetwithObject:
- (id)anArgument
前两种方法创建后,需要手机启动,启动的方法是:
- (void)start;
二、线程的同步与锁
要说明线程的同步与锁,最好的例子可能就是多个窗口同时售票的售票系统了。我们知道在java中,使用synchronized来同步,而iphone 虽 然没有提供类似java下的synchronized关键字,但提供了NSCondition对象接口。查看NSCondition的接口说明可以看 出,NSCondition是iphone下的锁对象,所以我们可以使用NSCondition实现iphone中的线程安全。这是来源于网上的一个例 子:
SellTicketsAppDelegate.h 文件
- //SellTicketsAppDelegate.h
- import < UIKit /UIKit.h >
- @interfaceSellTicketsAppDelegate:NSObject < UIApplicationDelegate > {
- inttickets;
- intcount;
- NSThread*ticketsThreadone;
- NSThread*ticketsThreadtwo;
- NSCondition*ticketsCondition;
- UIWindow*window;
- }
- @property(nonatomic,retain)IBOutletUIWindow*window;
- @end
- SellTicketsAppDelegate.m文件
- //SellTicketsAppDelegate.m
- import"SellTicketsAppDelegate.h"
- @implementationSellTicketsAppDelegate
- @synthesizewindow;
- -(void)applicationDidFinishLaunching:(UIApplication*)application{
- tickets = 100 ;
- count = 0 ;
- //锁对象
- ticketCondition =[[NSConditionalloc]init];
- ticketsThreadone =[[NSThreadalloc]initWithTarget:selfselector:@selector(run)object:nil];
- [ticketsThreadonesetName:@"Thread-1"];
- [ticketsThreadonestart];
- ticketsThreadtwo =[[NSThreadalloc]initWithTarget:selfselector:@selector(run)object:nil];
- [ticketsThreadtwosetName:@"Thread-2"];
- [ticketsThreadtwostart];
- //[NSThreaddetachNewThreadSelector:@selector(run)toTarget:selfwithObject:nil];
- //Overridepointforcustomizationafterapplicationlaunch
- [windowmakeKeyAndVisible];
- }
- -(void)run{
- while(TRUE){
- //上锁
- [ticketsConditionlock];
- if(tickets > 0){
- [NSThreadsleepForTimeInterval:0.5];
- count = 100 -tickets;
- NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThreadcurrentThread]name]);
- tickets--;
- }else{
- break;
- }
- [ticketsConditionunlock];
- }
- }
- -(void)dealloc{
- [ticketsThreadonerelease];
- [ticketsThreadtworelease];
- [ticketsConditionrelease];
- [windowrelease];
- [superdealloc];
- }
- @end
三、线程的交互
线程在运行过程中,可能需要与其它线程进行通信,如在主线程中修改界面等等,可以使用如下接口:
- (void)performSelectorOnMainThread:
- (SEL)aSelectorwithObject:
- (id)argwaitUntilDone:
- (BOOL)wait
由于在本过程中,可能需要释放一些资源,则需要使用NSAutoreleasePool来进行管理,如:
- (void)startTheBackgroundJob{
- NSAutoreleasePool* pool =[[NSAutoreleasePoolalloc]init];
- //todosomethinginyourthreadjob
- ...
- [selfperformSelectorOnMainThread:@selector(makeMyProgressBarMoving)withObject:nilwaitUntilDone:NO];
- [poolrelease];
- }
小结:
对于多线程,在一个程序中,一些独立运行的程序片断叫作线程,利用它编程的概念就叫作多线程处理。多线程处理一个常见的例子就是用户界面。利用线程,用户可按下一个按钮,然后程序会立即作出响应,而不是让用户等待程序完成了当前任务以后才开始响应