Obj-C 中与多线程相关的类有 NSOperation、NSOperationQueue 和 NSThread。NSOperation 类似与 Java 的 Runnable 接口,只是要实现的 NSOperation 的方法是 -(void) main; 当把 NSOperation 加到 NSOperationQueue 后,队列就会为每个 NSOperation 实例分配一个 NSThread 去启动它。NSOperation 执行完后会被 release 掉。
下面是使用 NSOperation 和 NSOperationQueue 的一段完整代码:
#import <Foundation/Foundation.h>
@interface MyOperation : NSOperation{
NSString *name;
}
@end
@implementation MyOperation
- (id) initWithName: (NSString *) theName {
self = [super init];
name = theName;
return self;
}
- (void) main {
NSLog(@"Thread %@ Start run: %@", name, [NSDate date]);
}
@end
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSOperation *operation1 = [[[MyOperation alloc] initWithName:@"One"] autorelease];
NSOperation *operation2 = [[[MyOperation alloc] initWithName:@"Two"] autorelease];
NSOperation *operation3 = [[[MyOperation alloc] initWithName:@"Three"] autorelease];
[queue addOperation:operation1];
[queue addOperation:operation2];
[queue addOperation:operation3];
[queue setMaxConcurrentOperationCount:2];//可设置同时并发数
sleep(50000);
[pool drain];
return 0;
}
执行结果输出中顺序是不定的,像:
011-08-09 14:20:54.144 TestObjC[3602:1c03] Thread Two Start run: 2011-08-09 06:20:54 +0000
2011-08-09 14:20:54.144 TestObjC[3602:1e03] Thread One Start run: 2011-08-09 06:20:54 +0000
2011-08-09 14:20:54.146 TestObjC[3602:1e03] Thread Three Start run: 2011-08-09 06:20:54 +0000
NSOperation 还有一个子类是 NSInvocationOperation,它与 NSOperation 的区别是可以指定线程要执行的实例的某个方法,而不只限制是 main 方法。
本文链接 http://unmi.cc/objective-c-snippets, 来自 隔叶黄莺 Unmi Blog