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

来源:互联网 发布:淘宝宝贝限时打折 编辑:程序博客网 时间:2024/05/17 21:38
  • 无论队列中所指定的执行的函数是同步还是异步,都会等待前一个任务执行完成后,再调度后面的任务
  • 要不要开线程由执行任务决定
    • 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 0