Objective-C(IOS)中多线程示例
来源:互联网 发布:linux 版本 编辑:程序博客网 时间:2024/04/20 03:27
// 初始化锁对象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,调出主线程中的方法去刷新。
0 0
- Objective-C(IOS)中多线程示例
- iOS Objective-C Block 的使用示例
- objective-c 中多线程 同步 之锁
- iOS中多线程编程示例【code】
- ios中Objective-C的@property详解
- iOS objective-c中数字转为罗马数字
- iOS (objective-c) 中的多线程互斥同步问题
- iOS (objective-c) 中的多线程互斥同步问题
- iOS (objective-c) 中的多线程互斥同步问题
- iOS (objective-c) 中的多线程互斥同步问题
- iOS (objective-c) 中的多线程互斥同步问题
- iOS (objective-c) 中的多线程互斥同步问题2
- Objective-c多线程
- Objective-c多线程
- Objective-c多线程
- Objective-c多线程
- objective-C多线程NSThread
- 【Objective-C】多线程
- ios 友盟集成分享 细节
- SQL2008R2的 遍历所有表更新统计信息和索引重建
- 51Nod 大数乘法
- 黑马程序员——反射机制的应用
- Hadoop中的FileSystem学习
- Objective-C(IOS)中多线程示例
- 获得系统相关信息
- CSS复习总结(6)
- C#中字符串的方法
- 51Nod A^BmodC
- 当不知所措时,做最简单的事
- Maven 基础知识大全
- Android选项卡动态滑动效果
- objective-C多线程NSThread