iOS中的主线程(Main Thread)与主队列(Main Q

2018-11-12  本文已影响0人  jackli007

最近在深入学习GCD有关知识。GCD中有两个很重要的概念:任务队列。虽然这两个概念都已经很了解,但是对线程thread)和队列queue)的关联和区别还是很稀里糊涂。通过多方搜索,发现两个blog很好的解释了这个问题。
CM Blog的个人博客
http://blog.corneliamu.com/archives/74
该篇博客中解答了一下三个问题:

我们都知道,主队列是系统为我们创建的串行队列,而且每个APP只有一个主队列,负责调度处理APP的唯一主线程的UI事件。所以在主队列的任务,即使是异步任务也只能在主线程中串行的执行。

主队列的任务一定在主线程执行,那么非主队列的任务可以在主线程里执行么?答案:当然可以。

- (void)asyncAndGlobalQueue {
    NSLog(@"begin --- %@",[NSThread currentThread]);
    //系统方法,获取全局的并行队列
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    for (NSInteger index = 0; index < 10 ;index ++) {
        dispatch_sync(globalQueue, ^{
            NSLog(@"index:%ld --- %@", index, [NSThread currentThread]);
        });
    }
    NSLog(@"end --- %@", [NSThread currentThread]);
}

打印结果:

2018-11-12 19:07:05.389994+0800 GCDDemo[1541:1198769] begin --- <NSThread: 0x101209580>{number = 1, name = main}
2018-11-12 19:07:05.390376+0800 GCDDemo[1541:1198769] index:0 --- <NSThread: 0x101209580>{number = 1, name = main}
2018-11-12 19:07:05.390641+0800 GCDDemo[1541:1198769] index:1 --- <NSThread: 0x101209580>{number = 1, name = main}
2018-11-12 19:07:05.390887+0800 GCDDemo[1541:1198769] index:2 --- <NSThread: 0x101209580>{number = 1, name = main}
2018-11-12 19:07:05.391374+0800 GCDDemo[1541:1198769] index:3 --- <NSThread: 0x101209580>{number = 1, name = main}
2018-11-12 19:07:05.391626+0800 GCDDemo[1541:1198769] index:4 --- <NSThread: 0x101209580>{number = 1, name = main}
2018-11-12 19:07:05.391865+0800 GCDDemo[1541:1198769] index:5 --- <NSThread: 0x101209580>{number = 1, name = main}
2018-11-12 19:07:05.392101+0800 GCDDemo[1541:1198769] index:6 --- <NSThread: 0x101209580>{number = 1, name = main}
2018-11-12 19:07:05.393473+0800 GCDDemo[1541:1198769] index:7 --- <NSThread: 0x101209580>{number = 1, name = main}
2018-11-12 19:07:05.395600+0800 GCDDemo[1541:1198769] index:8 --- <NSThread: 0x101209580>{number = 1, name = main}
2018-11-12 19:07:05.395870+0800 GCDDemo[1541:1198769] index:9 --- <NSThread: 0x101209580>{number = 1, name = main}
2018-11-12 19:07:05.396110+0800 GCDDemo[1541:1198769] end --- <NSThread: 0x101209580>{number = 1, name = main}
上一篇下一篇

猜你喜欢

热点阅读