GCD2:常用用法

1.一次性执行(单例)

+(SingletonExample *)sharedInstance
{
  static SingletonExample *sharedSingleton = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken,^(void) {
    sharedSingleton = [[self alloc] initialize];
 });
  return sharedSingleton;
}
2.按照一定顺序去执行  同步

- (void)demo
{
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
    //异步去执行
        dispatch_sync(queue, ^{
            NSLog(@"登陆 ---- %@",[NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"付费 ---- %@",[NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"下载 ---- %@",[NSThread currentThread]);
        });
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"通知用户  ---- %@",[NSThread currentThread]);
        });
    });
}

3.线程组的使用     模拟需求:要异步去下载3张图片,全部下载完成后通知用户

- (void)download3Image
{

    dispatch_group_t group = dispatch_group_create();
    
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    dispatch_group_async(group, queue, ^{
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"下载图片1 %@",[NSThread currentThread]);
        
    });
    
    dispatch_group_async(group, queue, ^{
        [NSThread sleepForTimeInterval:1.0];
        NSLog(@"下载图片2 %@",[NSThread currentThread]);
    });
    dispatch_group_async(group, queue, ^{
        [NSThread sleepForTimeInterval:2.5];
        NSLog(@"下载图片3 %@",[NSThread currentThread]);
    });
    
    //
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    NSLog(@"完成啦");

}

4.延迟操作

- (void)gcdDemo
{
    //dispatch_after 参数  1.延迟的时间  2.执行的队列   3.执行的任务
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 2.0);
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    void (^task)() = ^{
        NSLog(@"%@",[NSThread currentThread]);
    };
    dispatch_after(time, queue, task);
}

5.线程通讯

- (void)gcdDemo3
{
    //线程通信
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"拼命加载中,%@",[NSThread currentThread]);
        //[NSThread sleepForTimeInterval:2.0];
        dispatch_async(dispatch_get_main_queue(), ^{
            //在主线程中更新UI数据
            NSLog(@"在主线程中更新UI %@",[NSThread currentThread]);
        });
    });
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值