Objective-C(IOS)中多线程示例

复制代码
// 初始化锁对象
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,调出主线程中的方法去刷新。
复制代码
posted @   有容乃大  阅读(9258)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示