多线程GCD+同步执行+异步执行+并行执行+串行执行+重复、分组、延迟、障碍方法

1 初始化队列

   1> 主队列--串行队列
    dispatch_queue_t mainQueue=dispatch_get_main_queue();

    2> 全局并行队列
    dispatch_queue_t concu=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

    3> 创建串行队列
    dispatch_queue_t queueSerial=dispatch_queue_create("jereh1",DISPATCH_QUEUE_SERIAL);

    4> 创建并行队列
    dispatch_queue_t queueConcu=dispatch_queue_create("jereh2",DISPATCH_QUEUE_CONCURRENT);

2 同步执行

    1> 同步+串行
     dispatch_sync(queueSerial, ^{
        NSLog(@"同步串行对列1---%@",[NSThread currentThread]);
     });
     dispatch_sync(queueSerial, ^{
        NSLog(@"同步串行对列2---%@",[NSThread currentThread]);
     });

     dispatch_sync(mainQueue, ^{
        NSLog(@"--同步--串行--系统--主对列--死锁--不会执行--%@",[NSThread currentThread]);
     });

    2> 同步+并行
     dispatch_sync(queueConcu, ^{
        NSLog(@"同步并行队列1---%@",[NSThread currentThread]);
     });
    dispatch_sync(queueConcu, ^{
        NSLog(@"同步并行队列2---%@",[NSThread currentThread]);
     });

3 异步执行

    1> 异步执行+串行队列-----开启一个子线程,顺序执行
     dispatch_async(queueSerial, ^{
        NSLog(@"异步串行队列1---%@",[NSThread currentThread]);
      });
     dispatch_async(queueSerial, ^{
        NSLog(@"异步串行队列2---%@",[NSThread currentThread]);
     });

    2> 异步+并行-----开辟多个子线程,并发执行
     dispatch_async(queueConcu, ^{
        NSLog(@"异步并行队列1---%@",[NSThread currentThread]);
     });
     dispatch_async(queueConcu, ^{
        NSLog(@"异步并行队列2---%@",[NSThread currentThread]);
     });

4 GCD多线程的常用方法

1> 重复执行

   dispatch_apply(3, queueSerial, ^(size_t t) {
     //循环3次,t是当前执行的第几次
     [NSThread sleepForTimeInterval:2];
     NSLog(@"---%ld---%@",t,[NSThread currentThread]);
     //本身是主线程,位于同一个线程,放在异步里面使用变为子线程里面再开启返回主线程
    });
 });

2> 分组

 dispatch_group_t group=dispatch_group_create();
    dispatch_group_async(group, queueConcu, ^{
        [NSThread sleepForTimeInterval:1];
        NSLog(@"--1--");
    });
    dispatch_group_async(group, queueConcu, ^{
        [NSThread sleepForTimeInterval:2];
        NSLog(@"--2--");
    });
    dispatch_group_notify(group, queueConcu, ^{
        NSLog(@"结束了");//都结束的时候执行
    });

3> 延迟执行

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//等待2秒
        NSLog(@"==延迟执行===%@",[NSThread currentThread]);
});

4> 障碍

dispatch_async(queueConcu, ^{
        NSLog(@"=====0");
});
dispatch_barrier_async(queueConcu, ^{//设置障碍,后面的必须等到它执行完再执行
        [NSThread sleepForTimeInterval:2];
        NSLog(@"=====1");
});
dispatch_async(queueConcu, ^{
        NSLog(@"=====2");
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值