美文网首页
13.runloop 练习理解

13.runloop 练习理解

作者: ProfessorFan | 来源:发表于2022-05-23 17:53 被阅读0次

    问题

    1.练习题1
    当前代码 在主队列中执行

    
    // 这里是函数开始执行的地方
      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");
      });
    - (void)test
    {
        NSLog(@"2");
    }
    

    2.练习题2
    当前代码在主线程当中运行

    
        NSThread *thread = [[NSThread alloc] initWithBlock:^{
            NSLog(@"1");
        }];
        [thread start];
        
        [self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
    - (void)test
    {
        NSLog(@"2");
    }
    

    3.练习题3
    当前代码在主线程当中运行

    
        NSThread *thread = [[NSThread alloc] initWithBlock:^{
            NSLog(@"1");
            
            [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }];
        [thread start];
        
        [self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
        [self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
    
    - (void)test
    {
        NSLog(@"2");
    }
    

    答案

    1.练习题1

    结果: 打印 1 和 3
    分析: 子线程当中,默认不开启runloop [self performSelector:@selector(test) withObject:nil afterDelay:.0];这句代码本质是向当前子线程的runloop 当中添加了一个定时器,但是子线程当中runloop 默认不会启动,所以不会打印 2
    解决方案:
    在NSlog(@"3")前面添加 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];就可以了

    2.练习题2

    结果:打印 1 之后奔溃
    分析,由于子线程start 之后,没有相应开启runloop 给子线程保活,子线程已经执行完 block 就已经死掉了,之后在在子线程中执行 test函数,肯定就会奔溃.
    解决方案:
    在NSlog(@"1")下面添加保活代码:
    [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

    3.练习题3

    结果打印1 2 之后奔溃
    分析: [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    只会执行一次,相当于保证了一次,当第一次执行完之后,线程也就死掉来了,第二次在执行test 函数,也就导致奔溃
    解决方案:
    while (1){
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    } 这样就保证了线程一直存在

    相关文章

      网友评论

          本文标题:13.runloop 练习理解

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