多线程机制

一、主要有三种多线程编程机制

1、Thread

2、Cocoa operations

3、Grand Central Dispath (GCD)

二、Thread:使用NSThread或者直接从 NSObject 的类方法 performSelectorInBackground:withObject: 来创建一个线程

线程创建与启动
NSThread的创建主要有两种直接方式:

1  -(id)init;

2  -(id)initWithTargate selector:(SEL)selector object:(id)argument;

3 +(void)detachNewThreadSelector:(SEL)selector toTarget:(id)toTarget withObject:(id)anArgument
例如:[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];

NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(myThreadMainMethod:)object:nil];
[myThread start];

Cocoa operations是基于 Obective-C实现的,类 NSOperation 以面向对象的方式封装了用户需要执行的操作。

NSOperation 是一个抽象基类,我们必须使用它的子类。iOS 提供了两种默认实现:NSInvocationOperation 和 NSBlockOperation。

Grand Central Dispatch (GCD): iOS4 才开始支持,它提供了一些新的特性,以及运行库来支持多核并行编程。

三、线程同步和锁

  • - (void)applicationDidFinishLaunching:(UIApplication *)application {  
  •      tickets = 100;  
  •      count = 0;  
  •      // 锁对象  
  •      ticketCondition = [[NSCondition alloc] init];  
  •      ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  
  •      [ticketsThreadone setName:@"Thread-1"];  
  •      [ticketsThreadone start];   
  •      ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  
  •      [ticketsThreadtwo setName:@"Thread-2"];  
  •      [ticketsThreadtwo start];  
  •      //[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];  
  •       // Override point for customization after application launch  
  •      [window makeKeyAndVisible];   
  •  
  • }  
  • - (void)run{  
  •      while (TRUE) {  
  •      // 上锁  
  •          [ticketsCondition lock];  
  •          if(tickets > 0){  
  •              [NSThread sleepForTimeInterval:0.5];  
  •              count = 100 - tickets;  
  •              NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]);  
  •              tickets--;  
  •          }else{  
  •              break;  
  •          }  
  •          [ticketsCondition unlock];  
  •      }  
  • }  
四、线程的交互

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait 
由于在本过程中,可能需要释放一些资源,则需要使用NSAutoreleasePool来进行管理,如:

 
 
  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. }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值