iOS 多线程相关 线程组
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ dispatch_queue_t queue = dispatch_get_global_queue(0, 0); dispatch_async(queue, ^{ NSLog(@"1"); //这句话的本质是往runloop中添加定时器 [self performSelector:@selector(test) withObject:nil afterDelay:.0]; NSLog(@"3"); //若不启动runloop 子线程中是不会执行定时器的 打印结果为 1 3 执行了 打印结果为 1 3 2 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; }); } -(void)test{ NSLog(@"2"); }
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ NSThread *thred = [[NSThread alloc]initWithBlock:^{ NSLog(@"1"); //启动runloop 这时候runloop是处于休眠状态 等待后面给它发消息 ;如不执行 打印为1 并且崩溃 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]]; }]; [thred start]; [self performSelector:@selector(test) onThread:thred withObject:nil waitUntilDone:YES]; } -(void)test{ NSLog(@"2"); }
线程组
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ dispatch_queue_t queue = dispatch_queue_create("myqueue", DISPATCH_QUEUE_CONCURRENT); dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group, queue, ^{ for (int i =0; i<5; i++) { NSLog(@"1-%@",[NSThread currentThread]); } }); dispatch_group_async(group, queue, ^{ for (int i =0; i<5; i++) { NSLog(@"2-%@",[NSThread currentThread]); } }); // dispatch_group_notify(group, queue, ^{ // dispatch_async(dispatch_get_main_queue(), ^{ // for (int i =0; i<5; i++) { // NSLog(@"3-%@",[NSThread currentThread]); // } // }); // }); 等价于下面 dispatch_group_notify(group, dispatch_get_main_queue(), ^{ for (int i =0; i<5; i++) { NSLog(@"3-%@",[NSThread currentThread]); } }); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构