iOS:OC--多线程--GCD

同步任务,异步任务
同步:不开启子线程
异步:一定开启子线程
并行,串行:
并行:多个任务同时执行
串行:一个个执行
并行+异步:开启多个线程
并行+同步:在一个线程内执行多个任务
串行+异步:需要开启子线程
串行+同步:不需要开启子线程
使用 GCD 步骤:1.制定任务 2.添加到队列

  • ViewController.m
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //GCD---队列形式进行操作

    //异步
    [self asyncGlobalQueue];
    //同步
    [self syncGlobalQueue];
    [self loadData];
}
#pragma mark --- 使用异步方法添加到队列中
-(void)asyncGlobalQueue{
    //获取全局并发队列
    //获取全局并发队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
    //添加到任务队列中
    //异步
    dispatch_async(queue, ^{
        NSLog(@"1:%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"2:%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"3:%@",[NSThread currentThread]);
    });
}
#pragma mark --- 串行队列
-(void)sayncSerialQueue{
    //创建
    dispatch_queue_t queue = dispatch_queue_create("hello", NULL);
    //任务
    dispatch_async(queue, ^{
        NSLog(@"1:%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"2:%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"3:%@",[NSThread currentThread]);
    });
}
#pragma mark --- 使用同步方法添加到队列中
-(void)syncGlobalQueue{
    //并发
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
    //添加任务到队列
    dispatch_sync(queue, ^{
        NSLog(@"1:%@",[NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"2:%@",[NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"3:%@",[NSThread currentThread]);
    });
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)test
{
    //执行任务: GCD 中有两个执行任务函数
    //同步
    //1.dispatch_queue_t:队列
    //2.任务
//    dispatch_sync(<#dispatch_queue_t  _Nonnull queue#>, ^{
//        <#code#>
//    })
    //异步:
//    dispatch_sync(<#dispatch_queue_t  _Nonnull queue#>, <#^(void)block#>)
}
//https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497420262955&di=31fe0a09ecb071382b935112e90d1f89&imgtype=0&src=http%3A%2F%2Fv1.qzone.cc%2Fskin%2F201511%2F29%2F09%2F55%2F565a5b0d64410783.jpg%2521600x600.jpg
-(void)loadData
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *test = [session dataTaskWithURL:[NSURL URLWithString:@"url"]completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //更新 UI 事件
                
            });
        }
    }];
    //启动任务
    [test resume];
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容