美文网首页
iOS 多线程 相关面试题

iOS 多线程 相关面试题

作者: 奋斗的小马达 | 来源:发表于2021-02-21 22:29 被阅读0次

    一、请问下面代码的打印结果是什么?

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        dispatch_async(queue, ^{
            NSLog(@"1");
            [self performSelector:@selector(test) withObject:nil afterDelay:0.0];
            NSLog(@"3");
        });
    }
    
    - (void)test{
        NSLog(@"2");
    }
    
    答:打印结果是1、3
    原因是:
    1、performSelector:withObject:afterDelay:的本质是往Runloop中添加定时器
    2、子线程默认没有启动Runloop
    
    注意:只要有 afterDelay 延时操作的都是runloop的API
    
    

    二、请问下面代码的打印结果是什么?

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
        NSThread *thread = [[NSThread alloc]initWithBlock:^{
            NSLog(@"1");
        }];
        [thread start];
        
        [self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
    }
    - (void)test{
        NSLog(@"2");
    }
    
    答案:打印结果是 1 然后崩溃
    原因:
    thread 是子线程  子线程的runloop没有被开启 打印完1  子线程就结束退出了 
    此时再去往这个线程里添加任务 就会出现异常 然后崩溃
    
    

    以上两个面试题 都是考runloop的知识 了解runloop的底层原理上面的两道题就会迎刃而解

    相关文章

      网友评论

          本文标题:iOS 多线程 相关面试题

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