多线程相关的代码

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值