標籤:
GCD
全稱是Grand Central Dispatch
特點:
- 自動利用CPU的多核技術
- 自動管理線程的生命週期
使用步驟
- 定製任務
- 將任務添加隊列
各類隊列的特點
關於同步和非同步兩種執行方式
/** * 同步方式執行任務,不管是什麼隊列,都不會再開一個線程 */ dispatch_sync(<#dispatch_queue_t queue#>, ^{ <#code#> }) /** * 非同步方式執行任務,除了主隊列都會開啟一個新線程 */ dispatch_async(<#dispatch_queue_t queue#>, ^{ <#code#> })
建立隊列全域並發隊列
//獲得全域的並發隊列,第一個參數是優先順序,一般都是0,第二個參數是預留的,也為0 dispatch_get_global_queue(<#long identifier#>, <#unsigned long flags#>)
使用
dispatch_queue_t queue = dispatch_get_global_queue(0, 0); /** * 同步方式執行任務 */ dispatch_sync(queue, ^{ NSLog(@"%@", NSThread.currentThread);//{number = 1, name = main} }); /** * 非同步方式執行任務 */ dispatch_async(queue, ^{ NSLog(@"%@", NSThread.currentThread);//{number = 2, name = (null)} });
串列隊列
//第一個參數是隊列的名字,第二個參數為nildispatch_queue_create(<#const char *label#>, <#dispatch_queue_attr_t attr#>)
dispatch_queue_t queue = dispatch_queue_create("ttf", nil); /** * 同步方式執行任務 */ dispatch_sync(queue, ^{ NSLog(@"%@", NSThread.currentThread); }); /** * 非同步方式執行任務 */ dispatch_async(queue, ^{ NSLog(@"%@", NSThread.currentThread); });
使用主隊列
主隊列不能和同步執行方式一起使用,不然會死結
要使用非同步執行方式
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_queue_t queue = dispatch_get_main_queue(); /** * 同步方式執行任務 */// dispatch_sync(queue, ^{// NSLog(@"%@", NSThread.currentThread);// }); /** * 非同步方式執行任務 */ dispatch_async(queue, ^{ NSLog(@"%@", NSThread.currentThread); });
線程之間的通訊
dispatch_async(dispatch_get_global_queue(0, 0), ^{ // 執行耗時的非同步作業... dispatch_async(dispatch_get_main_queue(), ^{ // 回到主線程,執行UI重新整理操作 });});
//非同步下載圖片
UIImageView *imageView = [[UIImageView alloc] init]; imageView.frame = CGRectMake(100, 100, 100, 100); imageView.backgroundColor = [UIColor redColor]; [self.view addSubview:imageView]; dispatch_queue_t queue = dispatch_get_global_queue(0, 0); dispatch_async(queue, ^{ NSURL *url = [NSURL URLWithString:@"http://img6.cache.netease.com/cnews/2015/5/13/20150513153022b6a55.jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; // 這行會比較耗時 UIImage *image = [UIImage imageWithData:data]; dispatch_async(dispatch_get_main_queue(), ^{ imageView.image = image; }); });
一次性代碼
//代碼整個程式只被執行一次
static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{ // 只執行1次的代碼(這裡面預設是安全執行緒的)});
隊列組
可以吧幾個線程載入到隊列組裡面,等這個組裡面的線程全部執行完畢,再做其他事情
dispatch_group_t group = dispatch_group_create();dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 執行1個耗時的非同步作業});dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 執行1個耗時的非同步作業});dispatch_group_notify(group, dispatch_get_main_queue(), ^{ // 等前面的非同步作業都執行完畢後,回到主線程...});
【iOS開發-多線程】使用GCD建立多線程(iOS常用技術)