RunLoop-基础概念(初识篇)

2018-01-27  本文已影响5人  Zombie_Coder

学习这篇内容主要讲解RunLoop的概念,以及RunLoop和线程之间的关系。
当然提及RunLoop也离不开Autorealse Pool,本篇内容略有提及,但不重点阐述。
本篇内容是我自己对RunLoop概念的总结,和简单呈现,内容比较精炼。

概念

一、初识RunLoop

首先,我们在主线程中添加如下代码:

while (1) {
    NSLog(@"while begin");
    // the thread be blocked here
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    // this will not be executed
    NSLog(@"while end");
}

我们将上面代码在主线程运行,我们会发现while end没有执行,过一会又执行了,这是因为:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
    while (1) {
        NSLog(@"while begin");
        NSRunLoop *subRunLoop = [NSRunLoop currentRunLoop];
        [subRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        NSLog(@"while end");
    }
});

上面的代码是通过GCD开启全局的一个子线程,运行代码后,在子线程会无限循环的一直在跑,不会停!这是因为:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
    while (1) {
        NSPort *macPort = [NSPort port];
        NSLog(@"while begin");
        NSRunLoop *subRunLoop = [NSRunLoop currentRunLoop];
        [subRunLoop addPort:macPort forMode:NSDefaultRunLoopMode];
        [subRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        NSLog(@"while end");
        NSLog(@"%@",subRunLoop);
        
    }
});

上面的代码,运行后,会停在休眠的那一行代码,因为我们给RunLoop的model添加item.

小结:我们的RunLoop要想工作,必须要让它存在一个Item(source,observer或者timer),主线程之所以能够一直存在,并且随时准备被唤醒就是应为系统为其添加了很多Item.

上一篇 下一篇

猜你喜欢

热点阅读