• iOS: 常驻线程


    如何开启

    首先开启一个线程:

     1 @property (nonatomic, strong) NSThread *thread;
     2 
     3 - (IBAction)startAction:(id)sender {
     4     NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(start) object:nil];
     5     thread.name = @"com.live.thread";
     6     // 开启子线程
     7     [thread start];
     8     self.thread = thread;
     9 }
    10 
    11 - (void)start {
    12     NSLog(@"start----%@",[NSThread currentThread]);
    13 }
    14 
    15 - (IBAction)taskAction:(id)sender {
    16     /*
    17      如果设置wait为YES:等待当前线程执行完以后,主线程才会执行aSelector方法;
    18      设置为NO:不等待当前线程执行完,就在主线程上执行aSelector方法。
    19      如果,当前线程就是主线程,那么aSelector方法会马上执行。
    20      */
    21     [self performSelector:@selector(task) onThread:self.thread withObject:nil waitUntilDone:YES];
    22     
    23 }
    24 
    25 - (void)task {
    26     NSLog(@"task----%@",[NSThread currentThread]);
    27 }

    根据代码可知,执行startAction,打印

    start----<NSThread: 0x280b84c40>{number = 6, name = com.live.thread}

    我们知道一个线程执行完任务后就会自动销毁,再次调用此线程去执行任务即会报错:

    所以我们一般启动Runloop来使线程常驻,修改代码如下:

    1 - (void)start {
    2     NSLog(@"start----%@",[NSThread currentThread]);
    3     @autoreleasepool {
    4         do {
    5             [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
    6         } while (YES);
    7     }
    8 }

    便可成功执行task:

    start----<NSThread: 0x2807d5300>{number = 7, name = com.live.thread}

    task----<NSThread: 0x2807d5300>{number = 7, name = com.live.thread}

    如何停止

    代码如下:

     1 @property (nonatomic, assign) BOOL cancelled;
     2 
     3 - (IBAction)stopAction:(id)sender {
     4     [self performSelector:@selector(stop) onThread:self.thread withObject:nil waitUntilDone:NO];
     5 
     6     NSLog(@"退出runLoop");
     7 }
     8 
     9 - (void)start {
    10     NSLog(@"start----%@",[NSThread currentThread]);
    11     @autoreleasepool {
    12         do {
    13             [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
    14         } while (!self.cancelled);
    15     }
    16 }
    17 
    18 - (void)stop {
    19     self.cancelled = YES;
    20 }

    添加一个flag操控,执行stopAction后,再次操作task便又会报错,说明Runloop停止了

  • 相关阅读:
    曲演杂坛--Update的小测试
    曲演杂坛--使用TRY CATCH应该注意的一个小细节
    Backup--查看备份还原需要的空间
    INDEX--创建索引和删除索引时的SCH_M锁
    曲演杂坛--蛋疼的ROW_NUMBER函数
    曲演杂坛--使用ALTER TABLE修改字段类型的吐血教训
    曲演杂坛--查看那个应用连接到数据库
    TempDB--临时表的缓存
    (转)spark日志配置
    CDH版本java开发环境搭建
  • 原文地址:https://www.cnblogs.com/Walsh/p/13163288.html
Copyright © 2020-2023  润新知