Objective-C(IOS)中多线程示例
2015-12-19 13:47
435 查看
// 初始化锁对象 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]; - (void)run{ while (TRUE) { // 上锁 [ticketsCondition lock]; //dosomething.. [ticketsCondition unlock]; } } //释放资源。 - (void)dealloc { [ticketsThreadone release]; [ticketsThreadtwo release]; [ticketsCondition release]; [super dealloc]; } //线程在运行过程中,可能需要与其它线程进行通信,如在主线程中修改界面等等,可以使用如下接口: - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait 如: [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO]; //updateUI为和UI交换的方法名。 //NSAutoreleasePool启用。
使用另一种方法创建后台子线程:
//用到的类是NSThread类,这里使用detachNewTheadSelector:toTagaet:withObject创建一个线程。 //函数setupThread:(NSArray*)userInfor。通过userInfor将需要的数据传到线程中。 //函数定义: -(void)setupThread:(NSArray*)userInfor{ [NSThread detachNewThreadSelector:@selector(threadFunc:) toTarget:self withObject:(id)userInfor]; //注意threadFunc后面带冒号,方法threadFunc带id参数 } - (void)threadFunc:(id)userInfor{ NSAutoreleasePool*pool = [[NSAutoreleasePool alloc] init]; //。。。。需要做的处理。 //这里线程结束后立即返回 [self performSelectorOnMainThread:@selector(endThread) withObject:nil waitUntilDone:NO]; [pool release]; } //performSelectorOnMainThread通知主线程执行函数endThread。也可以使用performSelector:onThread:withObject:waitUntil 通知某线程执行线程结束后的处理。 //线程内不要刷新界面。如果需要刷新界面,通过performSelectorOnMainThread,调出主线程中的方法去刷新。
转自:http://www.cnblogs.com/mrhgw/archive/2012/06/30/2570834.html
相关文章推荐
- #Objective - C NSString的常用语法点总结
- Objective-C NSString类的常用方法
- How to gzip Data in Memory Using Objective-C
- Block Objects
- object 整理中..... 顶级页面
- The Objective-C runtime
- OObjective-c UIView 蒙层
- List.contains(Object o) 问题
- Playing with __attributes__ (二)
- Objective-C NSString类的常用方法
- Objective-C学习笔记---构造函数和析构函数
- scala学习笔记3-Actor、case class和object、loop和react的使用
- Scala Everything is an object
- Objective-C中NSArray的基本用法示例
- Objective-C block小解
- Objective-c语言_SNottification(通知)
- Objective-c语言_KVO
- Objective-c语言_观察者模式
- 《Object-OC 里面调用JS 和 接入是遇到的问题的解决》
- objective-c之谓词