iOS - 多线程

多线程在开发过程中的应用。有些业务逻辑的需要,需要我们使用到多线程。今天就常用的业务模式进行一下简单的说明。

  • 串行队列同步执行;

  • 串行队列异步执行;

  • 并行队列同步执行;

  • 并行队列异步执行;

  • 主队列异步执行;

  • 主队列同步执行;

  • 子线程下载主线程刷新;

  • 队列组的使用;

  • Thread;

  • operation;

  • 1、串行队列同步执行

串行队列同步执行 (在当前线程中顺序执行) 用于前后有依赖关系的处理 用的都是一条线程(在主线程中),不会开辟新线程。注意在主线程中耗时操作会造成主线程阻塞#

dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);//创建串行队列
    dispatch_sync(serialQueue, ^{
        DebugLog(@"串行队列同步执行- 1 == %@",[NSThread currentThread]);
    });
    dispatch_sync(serialQueue, ^{
        DebugLog(@"串行队列同步执行- 2 == %@",[NSThread currentThread]);
    });
    dispatch_sync(serialQueue, ^{
        for (int i = 0; i < 3; i++) {
            
            DebugLog(@"串行队列同步执行- 3 == %@",[NSThread currentThread]);
        }
    });
    //串行队列同步执行完以后走下面的代码(回到主线程)
    [SVProgressHUD showInfoWithStatus:@"串行队列同步执行执行完毕"];
    DebugLog(@"串行队列同步执行执行完毕 == %@",[NSThread currentThread]);

看一下执行顺序##

GCDLearnViewController.m:102    
串行队列同步执行- 1 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:105    
串行队列同步执行- 2 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:110    
串行队列同步执行- 3 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:110    
串行队列同步执行- 3 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:110    
串行队列同步执行- 3 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:115    
串行队列同步执行执行完毕 == <NSThread: 0x61800006fe40>{number = 1, name = main}
  • 2、串行队列异步执行

串行队列异步执行 (在当前线程中顺序执行) 用于前后有依赖关系的处理 用的都是一条线程(在子线程中),耗时操作和有依赖关系的处理,可以用此方法#

dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(serialQueue, ^{
        DebugLog(@"串行队列异步执行 - 1 == %@",[NSThread currentThread]);
    });
    dispatch_async(serialQueue, ^{
        for (int i = 0; i < 3; i++) {
            
            DebugLog(@"串行队列异步执行 - 2 == %@",[NSThread currentThread]);
        }
    });
    dispatch_async(serialQueue, ^{
        for (int i = 0; i < 3; i++) {
            
            DebugLog(@"串行队列异步执行 - 3 == %@",[NSThread currentThread]);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{//串行队列异步执行执行完毕 回到主线程
            [SVProgressHUD showInfoWithStatus:@"串行队列异步执行执行完毕"];
            DebugLog(@"串行队列异步执行执行完毕 == %@",[NSThread currentThread]);
        });
    });

看一下执行顺序##

GCDLearnViewController.m:122    
串行队列异步执行 - 1 == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:127    
串行队列异步执行 - 2 == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:127    
串行队列异步执行 - 2 == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:127    
串行队列异步执行 - 2 == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:133    
串行队列异步执行 - 3 == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:133    
串行队列异步执行 - 3 == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:133    
串行队列异步执行 - 3 == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:138    
串行队列异步执行执行完毕 == <NSThread: 0x61800006fe40>{number = 1, name = main}
  • 3、并行队列同步执行

并行队列同步执行 (number = 1, name = main) 在主线程中顺序执行;

dispatch_queue_t ConcurrentQueue = dispatch_queue_create("Concurrent", DISPATCH_QUEUE_CONCURRENT);
    dispatch_sync(ConcurrentQueue, ^{
        DebugLog(@"并行队列同步执行 - 1 == %@",[NSThread currentThread]);
    });
    dispatch_sync(ConcurrentQueue, ^{
        for (int i = 0; i < 3; i++) {
            
            DebugLog(@"并行队列同步执行 - 2 == %@",[NSThread currentThread]);
        }
    });
    dispatch_sync(ConcurrentQueue, ^{
        DebugLog(@"并行队列同步执行 - 3 == %@",[NSThread currentThread]);
    });

看一下执行顺序##

GCDLearnViewController.m:147    
并行队列同步执行 - 1 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:152    
并行队列同步执行 - 2 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:152    
并行队列同步执行 - 2 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:152    
并行队列同步执行 - 2 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:156    
并行队列同步执行 - 3 == <NSThread: 0x61800006fe40>{number = 1, name = main}
  • 4、并行队列异步执行

并行队列异步执行 开辟新线程 无序执行#

    dispatch_queue_t ConcurrentQueue = dispatch_queue_create("Concurrent", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(ConcurrentQueue, ^{
        DebugLog(@"并行队列异步执行 - 1 == %@",[NSThread currentThread]);
    });
    dispatch_async(ConcurrentQueue, ^{
        for (int i = 0; i < 3; i++) {
            
            DebugLog(@"并行队列异步执行 - 2 == %@",[NSThread currentThread]);
        }
    });
    dispatch_async(ConcurrentQueue, ^{
        DebugLog(@"并行队列异步执行 - 3 == %@",[NSThread currentThread]);
    });

看一下执行顺序##

GCDLearnViewController.m:164    
并行队列异步执行 - 1 == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:169    
并行队列异步执行 - 2 == <NSThread: 0x61800007bc40>{number = 6, name = (null)}
GCDLearnViewController.m:173    
并行队列异步执行 - 3 == <NSThread: 0x608000076440>{number = 7, name = (null)}
GCDLearnViewController.m:169    
并行队列异步执行 - 2 == <NSThread: 0x61800007bc40>{number = 6, name = (null)}
GCDLearnViewController.m:169    
并行队列异步执行 - 2 == <NSThread: 0x61800007bc40>{number = 6, name = (null)}
  • 5、主队列异步执行

主队列异步执行 ({number = 1, name = main}) 在主线程中顺序执行#

dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
        DebugLog(@"主队列异步执行 - 1 == %@",[NSThread currentThread]);
    });
    dispatch_async(mainQueue, ^{
        for (int i = 0; i < 3; i++) {
            
            DebugLog(@"主队列异步执行 - 2 == %@",[NSThread currentThread]);
        }
    });
    dispatch_async(mainQueue, ^{
        DebugLog(@"主队列异步执行 - 3 == %@",[NSThread currentThread]);
    });

看一下执行顺序##

GCDLearnViewController.m:181    
主队列异步执行 - 1 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:186    
主队列异步执行 - 2 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:186    
主队列异步执行 - 2 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:186    
主队列异步执行 - 2 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:190    
主队列异步执行 - 3 == <NSThread: 0x61800006fe40>{number = 1, name = main}
  • 6、主队列同步执行

主队列同步执行 会造成主线程卡死#

dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
        DebugLog(@"主队列同步执行 - 1 == %@",[NSThread currentThread]);
    });
    dispatch_async(mainQueue, ^{
        for (int i = 0; i < 3; i++) {
            
            DebugLog(@"主队列同步执行 - 2 == %@",[NSThread currentThread]);
        }
    });
    dispatch_async(mainQueue, ^{
        DebugLog(@"主队列同步执行 - 3 == %@",[NSThread currentThread]);
    });

看一下执行顺序##

GCDLearnViewController.m:199    
主队列同步执行 - 1 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:204    
主队列同步执行 - 2 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:204    
主队列同步执行 - 2 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:204    
主队列同步执行 - 2 == <NSThread: 0x61800006fe40>{number = 1, name = main}
GCDLearnViewController.m:208    
主队列同步执行 - 3 == <NSThread: 0x61800006fe40>{number = 1, name = main}
  • 7、子线程下载主线程刷新
dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i = 0; i < 3; i++) {
            DebugLog(@"下载操作");
        }
        dispatch_async(dispatch_get_main_queue(), ^{//这个也是子线程和主线程间的一种通信
            [SVProgressHUD showInfoWithStatus:@"下载完成,刷新主线程"];
            DebugLog(@"下载完成,刷新主线程");
        });
    });

看一下执行顺序##

GCDLearnViewController.m:216    
下载操作
GCDLearnViewController.m:216    
下载操作
GCDLearnViewController.m:216    
下载操作
GCDLearnViewController.m:220    
下载完成,刷新主线程
  • 8、队列组的使用

全部处理结束后刷新主线程#

dispatch_group_t group = dispatch_group_create();//队列组
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);//全局并发队列
    dispatch_group_async(group, queue, ^{//异步操作1
        for (int i = 0; i < 3; i ++) {
            DebugLog(@"异步操作1");
        }
    });
    dispatch_group_async(group, queue, ^{//异步操作2
        for (int i = 0; i < 3; i ++) {
            DebugLog(@"异步操作2");
        }
    });
    dispatch_group_async(group, queue, ^{//异步操作3
        for (int i = 0; i < 3; i ++) {
            DebugLog(@"异步操作3");
        }
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{//全部处理结束后刷新主线程
        [SVProgressHUD showInfoWithStatus:@"异步操作完成,回到主线程"];
        DebugLog(@"异步操作完成,回到主线程");
    });

看一下执行顺序##

GCDLearnViewController.m:231    
异步操作1
GCDLearnViewController.m:231    
异步操作1
GCDLearnViewController.m:231    
异步操作1
GCDLearnViewController.m:236    
异步操作2
GCDLearnViewController.m:241    
异步操作3
GCDLearnViewController.m:236    
异步操作2
GCDLearnViewController.m:241    
异步操作3
GCDLearnViewController.m:236    
异步操作2
GCDLearnViewController.m:241    
异步操作3
GCDLearnViewController.m:246    
异步操作完成,回到主线程
  • 9、Thread
NSThread *thread01 = [[NSThread alloc] initWithTarget:self selector:@selector(thread1) object:nil];
    thread01.name = @"北京售票窗口";
    [thread01 start];//需要启动
    NSThread *thread02 = [[NSThread alloc] initWithTarget:self selector:@selector(thread1) object:nil];
    thread02.name = @"广州售票窗口";
    [thread02 start];//需要启动
while (1) {
        @synchronized (self) {//加锁,防止资源争夺出现问题
            if (ticketCont > 0) {
                ticketCont--;
                DebugLog(@"%@",[NSString stringWithFormat:@"剩余票数:%d 窗口:%@", ticketCont, [NSThread currentThread].name]);
                [NSThread sleepForTimeInterval:.2f];
            }
            else{
                if ([[NSThread currentThread] isCancelled]) {
                    break;
                }
                else{
                    DebugLog(@"票卖完了 %@",[NSThread currentThread]);
                    [[NSThread currentThread] cancel];
                }
            }
        }
    }

看一下打印##

GCDLearnViewController.m:325    
剩余票数:9 窗口:北京售票窗口
GCDLearnViewController.m:325    
剩余票数:8 窗口:广州售票窗口
GCDLearnViewController.m:325    
剩余票数:7 窗口:北京售票窗口
GCDLearnViewController.m:325    
剩余票数:6 窗口:广州售票窗口
GCDLearnViewController.m:325    
剩余票数:5 窗口:北京售票窗口
GCDLearnViewController.m:325    
剩余票数:4 窗口:广州售票窗口
GCDLearnViewController.m:325    
剩余票数:3 窗口:北京售票窗口
GCDLearnViewController.m:325    
剩余票数:2 窗口:广州售票窗口
GCDLearnViewController.m:325    
剩余票数:1 窗口:北京售票窗口
GCDLearnViewController.m:325    
剩余票数:0 窗口:广州售票窗口
GCDLearnViewController.m:333    
票卖完了 <NSThread: 0x60000007e640>{number = 8, name = 北京售票窗口}
GCDLearnViewController.m:333    
票卖完了 <NSThread: 0x610000269cc0>{number = 9, name = 广州售票窗口}
  • 10、Operation
NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operation1:) object:nil];
    op1.name = @"北京售票窗口";
    
    NSInvocationOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operation1:) object:nil];
    op2.name = @"广州售票窗口";
    
    //如果不添加到NSOperationQueue里面就不会开启线程,会在当前线程中执行
    operationQueue = [[NSOperationQueue alloc] init];//默认是并发的,如果想实现串行, 那么就设置队列的maxConcurrentOperationCount = 1
    [operationQueue addOperation:op1];
    [operationQueue addOperation:op2];
while (1) {
        @synchronized (self) {//加锁,防止资源争夺出现问题
            if (ticketCont > 0) {
                ticketCont--;
                DebugLog(@"%@",[NSString stringWithFormat:@"剩余票数:%d 窗口:%@ == %@", ticketCont, op.name,[NSThread currentThread]]);
            }
            else{
                DebugLog(@"票卖完了 %@",[NSThread currentThread]);
                break;
            }
        }
    }

看一下打印##

GCDLearnViewController.m:352    
剩余票数:9 窗口:(null) == <NSThread: 0x61800007ea00>{number = 11, name = (null)}
GCDLearnViewController.m:352    
剩余票数:8 窗口:(null) == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:352    
剩余票数:7 窗口:(null) == <NSThread: 0x61800007ea00>{number = 11, name = (null)}
GCDLearnViewController.m:352    
剩余票数:6 窗口:(null) == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:352    
剩余票数:5 窗口:(null) == <NSThread: 0x61800007ea00>{number = 11, name = (null)}
GCDLearnViewController.m:352    
剩余票数:4 窗口:(null) == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:352    
剩余票数:3 窗口:(null) == <NSThread: 0x61800007ea00>{number = 11, name = (null)}
GCDLearnViewController.m:352    
剩余票数:2 窗口:(null) == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:352    
剩余票数:1 窗口:(null) == <NSThread: 0x61800007ea00>{number = 11, name = (null)}
GCDLearnViewController.m:352    
剩余票数:0 窗口:(null) == <NSThread: 0x6180000755c0>{number = 5, name = (null)}
GCDLearnViewController.m:355    
票卖完了 <NSThread: 0x61800007ea00>{number = 11, name = (null)}
GCDLearnViewController.m:355    
票卖完了 <NSThread: 0x6180000755c0>{number = 5, name = (null)}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • 一、前言 上一篇文章iOS多线程浅汇-原理篇中整理了一些有关多线程的基本概念。本篇博文介绍的是iOS中常用的几个多...
    nuclear阅读 1,994评论 6 18
  • 一、前言 本篇博文介绍的是iOS中常用的几个多线程技术: NSThread GCD NSOperation 由于a...
    和珏猫阅读 535评论 0 1
  • 1. GCD简介 什么是GCD呢?我们先来看看百度百科的解释简单了解下概念 引自百度百科:Grand Centra...
    千寻_544f阅读 340评论 0 0
  • 在这篇文章中,我将为你整理一下 iOS 开发中几种多线程方案,以及其使用方法和注意事项。当然也会给出几种多线程的案...
    张战威ican阅读 582评论 0 0
  • 长亭外,古道边,芳草碧连天。晚风拂柳笛声残,夕阳山外山。天之涯,地之角,知交半零落。一壶浊酒尽余欢,今宵别梦寒。—...
    旧城xu阅读 1,561评论 0 0