GCD同步任务作用

2017-02-27  本文已影响61人  遥远不是北_

GCD同步任务作用

代码演练

建立依赖关系

//点击屏幕触发事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    //调用
    [self GCDDemo];
}
- (void)GCDDemo {
    
    //全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    //同步任务加载
    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]);
    });
    
}

2017-02-23 20:56:19.702 同步任务作用[8315:462677] 登录-<NSThread: 0x608000068200>{number = 1, name = main}
2017-02-23 20:56:19.702 同步任务作用[8315:462677] 付费-<NSThread: 0x608000068200>{number = 1, name = main}
2017-02-23 20:56:19.703 同步任务作用[8315:462677] 下载-<NSThread: 0x608000068200>{number = 1, name = main}
2017-02-23 20:56:19.703 同步任务作用[8315:462677] 通知用户-<NSThread: 0x608000068200>{number = 1, name = main}

依赖关系优化

- (void)GCDDemo {
    
    //全局队列
    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]);
        });
    });
    
}
2017-02-23 21:01:48.256 同步任务作用[8423:467767] 登录-<NSThread: 0x600000075100>{number = 3, name = (null)}
2017-02-23 21:01:48.256 同步任务作用[8423:467767] 付费-<NSThread: 0x600000075100>{number = 3, name = (null)}
2017-02-23 21:01:48.256 同步任务作用[8423:467767] 下载-<NSThread: 0x600000075100>{number = 3, name = (null)}
2017-02-23 21:01:48.257 同步任务作用[8423:467733] 通知用户-<NSThread: 0x60000006b180>{number = 1, name = main}

总结:

上一篇下一篇

猜你喜欢

热点阅读