一、主要有三种多线程编程机制
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来进行管理,如:
- - (void)startTheBackgroundJob {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- // to do something in your thread job
- ...
- [self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO];
- [pool release];
- }