iOS 之NSThread

iPhone 中的线程应用并不是无节制的,官方给出的资料显示iPhone OS下的主线程的堆栈大小是1M,第二个线程开始都是512KB。并且该值不能通过编译器开关或线程API函数来更改。

  只有主线程有直接修改UI的能力。

一、 NSOperation和NSOperationQueue

  1、一个继承自  NSOperation的操作类,该类的实现中必须有 - (void)main方法的。

  2、使用NSOperation的最简单方法就是将其放入NSOperationQueue中。

    一旦一个操作被加入队列,该队列就会启动并开始处理它(即调用该操作类的main方法)。一旦该操作完成队列就会释放它。

[cpp]  view plain copy
  1. self.queue = [[NSOperationQueuealloc] init];  
  2.   
  3.  ArticleParseOperation *parser = [[ArticleParseOperationalloc] initWithData:filePathdelegate:self]; 
  4.   
  5.  [queue addOperation:parser];  
  6.   
  7.  [parser release];  
  8.   
  9. [queuerelease];  
[cpp]  view plain copy
  1. self.queue = [[NSOperationQueuealloc] init];  
  2.   
  3.  ArticleParseOperation *parser = [[ArticleParseOperationalloc] initWithData:filePathdelegate:self];  
  4.   
  5.  [queue addOperation:parser];  
  6.   
  7.  [parser release];  
  8.   
  9. [queuerelease];  


  3、可以给操作队列设置最多同事运行的操作数: [queue setMaxConcurrentOperationCount:2];

二、NSThread<转>

一、线程创建与启动
线程创建主要有二种方式:

[cpp]  view plain copy
  1. - (id)init; // designated initializer 
  2. - (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument; 
[cpp]  view plain copy
  1. - (id)init; // designated initializer  
  2. - (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;  

当然,还有一种比较特殊,就是使用所谓的convenient method,这个方法可以直接生成一个线程并启动它,而且无需为线程的清理负责。这个方法的接口是:
[cpp]  view plain copy
  1. + (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument 
[cpp]  view plain copy
  1. + (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument  

前两种方法创建后,需要手机启动,启动的方法是:
  1. <span>-</span> <span>(</span><span>void</span><span>)</span>start<span>;</span> 
  1. <span>-</span> <span>(</span><span>void</span><span>)</span>start<span>;</span>  

二、线程的同步与锁
要说明线程的同步与锁,最好的例子可能就是多个窗口同时售票的售票系统了。我们知道在java中,使用synchronized来同步,而iphone虽然没有提供类似java下的synchronized关键字,但提供了NSCondition对象接口。查看NSCondition的接口说明可以看出,NSCondition是iphone下的锁对象,所以我们可以使用NSCondition实现iphone中的线程安全。这是来源于网上的一个例子:
SellTicketsAppDelegate.h 文件

[cpp]  view plain copy
  1. //  SellTicketsAppDelegate.h 
  2. import <UIKit/UIKit.h>  
  3.    
  4. @interface SellTicketsAppDelegate : NSObject <UIApplicationDelegate> { 
  5.      int tickets;  
  6.      int count;  
  7.      NSThread* ticketsThreadone;  
  8.      NSThread* ticketsThreadtwo;  
  9.      NSCondition* ticketsCondition;  
  10.      UIWindow *window;  
  11. }  
  12. @property (nonatomic, retain) IBOutlet UIWindow *window;  
  13. @end  
[cpp]  view plain copy
  1. //  SellTicketsAppDelegate.h  
  2. import <UIKit/UIKit.h>  
  3.    
  4. @interface SellTicketsAppDelegate : NSObject <UIApplicationDelegate> {  
  5.      int tickets;  
  6.      int count;  
  7.      NSThread* ticketsThreadone;  
  8.      NSThread* ticketsThreadtwo;  
  9.      NSCondition* ticketsCondition;  
  10.      UIWindow *window;  
  11.  }  
  12. @property (nonatomic, retain) IBOutlet UIWindow *window;  
  13. @end  

SellTicketsAppDelegate.m 文件
[cpp]  view plain copy
  1. //  SellTicketsAppDelegate.m 
  2. import "SellTicketsAppDelegate.h"  
  3.    
  4. @implementation SellTicketsAppDelegate  
  5. @synthesize window;  
  6.    
  7. - (void)applicationDidFinishLaunching:(UIApplication *)application { 
  8.      tickets = 100;  
  9.      count = 0;  
  10.      // 锁对象  
  11.      ticketCondition = [[NSCondition alloc] init];  
  12.      ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; 
  13.      [ticketsThreadone setName:@"Thread-1"]; 
  14.      [ticketsThreadone start];    
  15.    
  16.    
  17.      ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; 
  18.      [ticketsThreadtwo setName:@"Thread-2"]; 
  19.      [ticketsThreadtwo start];  
  20.      //[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil]; 
  21.       // Override point for customization after application launch 
  22.      [window makeKeyAndVisible];   
  23.    
  24. }  
  25.    
  26. - (void)run{  
  27.      while (TRUE) {  
  28.         // 上锁  
  29.          [ticketsCondition lock];  
  30.          if(tickets > 0){  
  31.              [NSThread sleepForTimeInterval:0.5];  
  32.              count = 100 - tickets;  
  33.              NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]); 
  34.              tickets--;  
  35.          }else{  
  36.              break;  
  37.          }  
  38.          [ticketsCondition unlock];  
  39.      }  
  40. }  
  41.    
  42. - (void)dealloc {  
  43.     [ticketsThreadone release];  
  44.      [ticketsThreadtwo release];  
  45.      [ticketsCondition release];   
  46.      [window release];  
  47.      [super dealloc];  
  48. }  
  49. @end  
[cpp]  view plain copy
  1. //  SellTicketsAppDelegate.m  
  2. import "SellTicketsAppDelegate.h"  
  3.    
  4. @implementation SellTicketsAppDelegate  
  5. @synthesize window;  
  6.    
  7. - (void)applicationDidFinishLaunching:(UIApplication *)application {  
  8.      tickets = 100;  
  9.      count = 0;  
  10.      // 锁对象  
  11.      ticketCondition = [[NSCondition alloc] init];  
  12.      ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  
  13.      [ticketsThreadone setName:@"Thread-1"];  
  14.      [ticketsThreadone start];    
  15.    
  16.    
  17.      ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  
  18.      [ticketsThreadtwo setName:@"Thread-2"];  
  19.      [ticketsThreadtwo start];  
  20.      //[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];  
  21.       // Override point for customization after application launch  
  22.      [window makeKeyAndVisible];   
  23.    
  24.  }  
  25.    
  26. - (void)run{  
  27.      while (TRUE) {  
  28.         // 上锁  
  29.          [ticketsCondition lock];  
  30.          if(tickets > 0){  
  31.              [NSThread sleepForTimeInterval:0.5];  
  32.              count = 100 - tickets;  
  33.              NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]);  
  34.              tickets--;  
  35.          }else{  
  36.              break;  
  37.          }  
  38.          [ticketsCondition unlock];  
  39.      }  
  40.  }  
  41.    
  42. - (void)dealloc {  
  43.     [ticketsThreadone release];  
  44.      [ticketsThreadtwo release];  
  45.      [ticketsCondition release];   
  46.      [window release];  
  47.      [super dealloc];  
  48. }  
  49. @end  

三、线程的交互
线程在运行过程中,可能需要与其它线程进行通信,如在主线程中修改界面等等,可以使用如下接口:
[cpp]  view plain copy
  1. - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait 
[cpp]  view plain copy
  1. - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait  

由于在本过程中,可能需要释放一些资源,则需要使用NSAutoreleasePool来进行管理,如:
[cpp]  view plain copy
  1. - (void)startTheBackgroundJob { 
  2.     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
  3.     // to do something in your thread job 
  4.     ...  
  5.     [self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO]; 
  6.     [pool release];  
  7. }  
[cpp]  view plain copy
  1. - (void)startTheBackgroundJob {  
  2.     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
  3.     // to do something in your thread job  
  4.     ...  
  5.     [self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO];  
  6.     [pool release];  
  7. }  

如果你什么都不考虑,在线程函数内调用 autorelease 、那么会出现下面的错误:
NSAutoReleaseNoPool(): Object 0x********* of class NSConreteData autoreleased with no pool in place ….

四、关于线程池,大家可以查看NSOperation的相关资料。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值