RunLoop和线程关系

2018-03-21  本文已影响39人  骑着毛驴走起来

1.runloop与线程是一一对应的,一个runloop对应一个核心的线程,为什么说是核心的,是因为runloop是可以嵌套的,但是核心的只能有一个,他们的关系保存在一个全局的字典里。

2.runloop是来管理线程的,当线程的runloop被开启后,线程会在执行完任务后进入休眠状态,有了任务就会被唤醒去执行任务。

3.runloop在第一次获取时被创建,在线程结束时被销毁。

4.对于主线程来说,runloop在程序一启动就默认创建好了。

5.对于子线程来说,runloop是懒加载的,只有当我们使用的时候才会创建,所以在子线程用定时器要注意:确保子线程的runloop被创建,不然定时器不会回调。

6.子线程中使用定时器,需将定时器添加至RunLoop中。

    dispatch_queue_t queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_SERIAL);

    dispatch_async(queue, ^{

         NSLog(@"1");

        // 第1种方式

        //        NSTimer *timer1 =[NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];

        //        [[NSRunLoop currentRunLoop] run];

        //第2种方式

        //此种方式创建的timer没有添加至runloop中

        NSTimer *timer2 = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];

        [[NSRunLoop currentRunLoop] addTimer:timer2 forMode:NSDefaultRunLoopMode];

        [[NSRunLoop currentRunLoop] run];//已经将nstimer添加到NSRunloop中了

        NSLog(@"2");

        //注意子线程中不会执行延时操作

        [self performSelector:@selector(timerAction) withObject:nil afterDelay:5];

   });

上一篇 下一篇

猜你喜欢

热点阅读