以下是使用 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);
}
}];
```