多线程——GCD(串行队列)

  • 无论队列中所指定的执行的函数是同步还是异步,都会等待前一个任务执行完成后,再调度后面的任务
  • 要不要开线程由执行任务决定
    • dispatch_sync 不开
    • dispatch_async 开
  • 开几条线程由谁决定
    • 串行队列,异步执行,开几条,由底层线程池决定
    • 串行队列,同步执行,不开线程

串行队列,异步执行任务

 - (void)gcdDemo1 {
    for (NSInteger index = 0; index < 10; index ++) {
        // 创建一个串行队列
        dispatch_queue_t queue =  dispatch_queue_create("zy", NULL);
        // 将任务添加到队列中
        dispatch_async(queue, ^{
            NSLog(@"%@---%zd",[NSThread currentThread],index);
        });
    }
}

结果如下:
结果

  • 结论:
    • 开线程,开几条由底层线程池决定
      • 执行顺序:乱序

串行队列,同步执行任务

 - (void)gcdDemo2 {
    for (NSInteger index = 0; index < 10; index ++) {
        // 将任务添加到队列中
        // 同步任务:必须等待任务执行完毕,后续的代码才会执行
        dispatch_sync(dispatch_queue_create("zy", DISPATCH_QUEUE_SERIAL), ^{
            NSLog(@"%@---%zd",[NSThread currentThread],index);
        });

        NSLog(@"index = %zd",index);
    }
    NSLog(@"over");

}
  • 结论
    • 不会开线程
    • 顺序执行

串行队列,异步执行

 - (void)gcdDemo3 {
    // 创建串行队列
    // 串行队列的特点:队列中的任务必须按顺序执行。

    dispatch_queue_t queue =  dispatch_queue_create("zy", NULL);

    for (NSInteger index = 0; index < 10; index ++) {
        // 将任务添加到队列中
        dispatch_async(queue, ^{
            NSLog(@"%@---%zd",[NSThread currentThread],index);
        });
    }
}
  • 结论:开一条线程,顺序执行

串行队列,同步

 - (void)gcdDemo4 {
    // 创建串行队列
    // 串行队列的特点:队列中的任务必须按顺序执行。
    // 不管是同步还是异步,串行队列中的任务都是按顺序执行,异步会开线程,开一条。同步不开线程,在当前线程执行任务。
    dispatch_queue_t queue =  dispatch_queue_create("zy", NULL);
    for (NSInteger index = 0; index < 10; index ++) {
        // 将任务添加到队列中
        dispatch_sync(queue, ^{
            NSLog(@"%@---%zd",[NSThread currentThread],index);
        });
    }
}
  • 结论,不开线程 顺序执行
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值