美文网首页
【iOS重学】线程保活

【iOS重学】线程保活

作者: 重庆妹子在霾都 | 来源:发表于2023-02-14 10:44 被阅读0次

写在前面

本文主要讲一下线程保活是什么、线程保活的意义、如何实现线程保活。

线程保活

线程生命周期

1.png
【新建】:创建一个线程对象。
【就绪】:线程调用start方法,将线程加入可调度线程池中,等着CPU的调度。
【运行】:CPU调度当前线程执行。
【阻塞】:当满足某个预设的条件时(比如休眠或者同步锁)会阻塞线程执行,重新将线程设置为【就绪】状态。
【死亡】:线程任务执行完毕或强制退出,线程生命周期结束。

什么是线程保活

线程保活:一般情况下,当线程执行玩一次任务之后需要进行资源回收也就意味着生命周期结束,线程保活就是保证线程的生命周期不结束。

线程保活的应用场景

当一个任务随时都有可能去执行它,那么这个任务应该放在子线程去执行,并且让子线程一直存活,避免频繁创建线程而造成的性能损耗。
大家如果看过AFNetworking的源码就会看到框架里面是有用到线程保活的。

如何实现线程保活

// WWPermenantThread 类
@interface WWPermenantThread : NSObject

/**
 关闭线程
 */
- (void)stop;

/// 在保活的线程里面执行的任务
/// @param target 目标对象
/// @param action selector
/// @param object object
- (void)excuteTaskWithTarget:(id)target action:(SEL)action object:(id)object;

/// 在保活的线程里执行任务
/// @param task 执行的任务
- (void)excuteTask:(void(^)(void))task;

@end

@interface WWPermenantThread ()

@property (nonatomic, strong) NSThread *innerThread;
@property (nonatomic, assign) BOOL isStopped;

@end

@implementation WWPermenantThread

- (void)dealloc {
    NSLog(@"%s",__func__);
    [self stop];
}

- (instancetype)init {
  if (self = [super init]) {
    self.isStopped = NO;

    __weak typeof(self) weakSelf = self;
    self.innerThread = [[NSThread alloc] initWithBlock:^{
      // 添加Port到RunLoop
      [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
      while (weakSelf && !weakSelf.isStopped) {
        // 开启RunLoop
          [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
      }
    }];
    [self.innerThread start];
  }
  return self;
}

- (void)run {
  if (!self.innerThread) {
      return;
  }
  [self.innerThread start];
}

- (void)stop {
  if (!self.innerThread) {
      return;
  }
  [self performSelector:@selector(__stop) onThread:self.innerThread withObject:nil waitUntilDone:YES];
}

- (void)__stop {
  self.isStopped = YES;
  // 退出当前RunLoop
  CFRunLoopStop(CFRunLoopGetCurrent());
  self.innerThread = nil;
}

- (void)excuteTaskWithTarget:(id)target action:(SEL)action object:(id)object {
  if (!self.innerThread) {
      return;
  }
  [self performSelector:action onThread:self.innerThread withObject:object waitUntilDone:NO ];
}

- (void)excuteTask:(void (^)(void))task {
  if (!self.innerThread || !task) {
      return;
  }
  [self performSelector:@selector(__excuteTask:) onThread:self.innerThread withObject:task waitUntilDone:NO ];
}

- (void)__excuteTask:(void(^)(void))task {
  task();
}

@end

如何使用线程保活

- (void)viewDidLoad {
  [super viewDidLoad];
  // 创建一个线程对象
  self.thread = [[WWPermenantThread alloc] init];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
  [self.thread excuteTask:^{
      NSLog(@"执行任务 - %@", [NSThread currentThread]);
  }];
}

执行结果:

2023-02-15 10:18:56.211402+0800 线程保活Demo1[10526:21512893] 执行任务 - <NSThread: 0x600002e99680>{number = 9, name = (null)}
2023-02-15 10:18:56.830085+0800 线程保活Demo1[10526:21512893] 执行任务 - <NSThread: 0x600002e99680>{number = 9, name = (null)}
2023-02-15 10:18:57.279150+0800 线程保活Demo1[10526:21512893] 执行任务 - <NSThread: 0x600002e99680>{number = 9, name = (null)}
2023-02-15 10:18:58.212741+0800 线程保活Demo1[10526:21512893] 执行任务 - <NSThread: 0x600002e99680>{number = 9, name = (null)}
2023-02-15 10:19:32.672529+0800 线程保活Demo1[10526:21512038] -[OneViewController dealloc]
2023-02-15 10:19:32.672800+0800 线程保活Demo1[10526:21512038] -[WWPermenantThread dealloc]

写在最后

关于如何实现线程保活的笔记就记录到这里了,如有错误请多多指教,最后欢迎去我的个人技术博客逛逛。

相关文章

  • iOS底层原理——浅谈RunLoop

    RunLoop应用:线程保活 线程保活、控制销毁 iOS-浅谈RunLoop8iOS底层原理总结 - RunLoo...

  • iOS NSThread 保活线程代码封装

    iOS NSThread 保活线程代码封装

  • iOS 线程保活

    [self performSelectorInBackground:@selector(dealInsertMo...

  • iOS 线程保活

    1、线程保活管理类.h文件 // // ZFPermenantThread.h // ZFThread // //...

  • iOS线程保活

    简介 大家好!我是Tony,一个热爱技术,希望运用技术改变生活的的追梦男孩。闲话不多说,今天聊聊iOS的线程保活。...

  • iOS:线程保活

    自定义子线程MZChildThread 使用

  • iOS 线程保活

    开发中,经常会遇到将耗时操作放到子线程中执行,来提升应用性能的场景。当子线程中的任务执行完毕后,线程就被立刻销毁。...

  • iOS线程保活

    一.什么是线程保活 如图1所以,任务执行完成后,线程会退出。线程的创建和销毁比较耗性能,如果需要在一条线程中频繁的...

  • iOS 线程保活

    JXPermenantThread 子线程保活: 快速创建子线程,让子线程一直存活,并提供执行任务的block,直...

  • iOS 题目详解 部分二

    主要讲解子线程的保活方式, 以及 Autorelease 对象的释放时机 iOS 题目详解 部分一iOS 题目...

网友评论

      本文标题:【iOS重学】线程保活

      本文链接:https://www.haomeiwen.com/subject/rglekdtx.html