iOS中的线程保活用oc代码实现

动态 未结 0 97
小小草
小小草 LV1 2023年9月23日 23:40 发表
以下是使用 Objective-C 代码实现线程保活的示例: 1. 使用 NSRunLoop ```objective-c // 创建一个新的线程 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; [thread start]; // 在新线程中执行任务 - (void)run { // 获取当前线程的 RunLoop NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; // 创建一个定时器,并将其加入到 RunLoop 中 NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES]; [runLoop addTimer:timer forMode:NSDefaultRunLoopMode]; // 启动 RunLoop,使线程一直处于运行状态 [runLoop run]; } // 定时器回调方法 - (void)timerAction { NSLog(@"timer fired"); } ``` 2. 使用 GCD ```objective-c // 创建一个新的线程 dispatch_queue_t queue = dispatch_queue_create("com.example.thread", DISPATCH_QUEUE_SERIAL); dispatch_async(queue, ^{ // 在新线程中执行任务 while (YES) { NSLog(@"task running"); sleep(1); } }); ``` 3. 使用 NSOperationQueue ```objective-c // 创建一个新的线程 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperationWithBlock:^{ // 在新线程中执行任务 while (YES) { NSLog(@"task running"); sleep(1); } }]; ```
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复