同步任務(wù),異步任務(wù)
同步:不開啟子線程
異步:一定開啟子線程
并行,串行:
并行:多個任務(wù)同時執(zhí)行
串行:一個個執(zhí)行
并行+異步:開啟多個線程
并行+同步:在一個線程內(nèi)執(zhí)行多個任務(wù)
串行+異步:需要開啟子線程
串行+同步:不需要開啟子線程
使用 GCD 步驟:1.制定任務(wù) 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{
//獲取全局并發(fā)隊列
//獲取全局并發(fā)隊列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
//添加到任務(wù)隊列中
//異步
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{
//創(chuàng)建
dispatch_queue_t queue = dispatch_queue_create("hello", NULL);
//任務(wù)
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{
//并發(fā)
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
//添加任務(wù)到隊列
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
{
//執(zhí)行任務(wù): GCD 中有兩個執(zhí)行任務(wù)函數(shù)
//同步
//1.dispatch_queue_t:隊列
//2.任務(wù)
// 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 事件
});
}
}];
//啟動任務(wù)
[test resume];
}
@end