一、關于GCD
GCD全稱是Grand Central Dispatch,是蘋果公司為多核的并行運算提出的解決方案, GCD會自動利用更多的CPU內核(比如雙核、四核),GCD會自動管理線程的生命周期(創(chuàng)建線程、調度任務、銷毀線程)

二、關于同步、異步、并發(fā)、串行
同步和異步決定了要不要開啟新的線程
同步:在當前線程中執(zhí)行任務,不具備開啟新線程的能力
異步:在新的線程中執(zhí)行任務,具備開啟新線程的能力
并發(fā)和串行決定了任務的執(zhí)行方式
并發(fā):多個任務并發(fā)(同時)執(zhí)行
串行:一個任務執(zhí)行完畢后,再執(zhí)行下一個任務
三、代碼示例
1、用異步函數(shù)往并發(fā)隊列中添加任務
//異步并發(fā)
-(void)ybbf{
????//獲取全局并發(fā)隊列
????dispatch_queue_t queue =? dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
????//2.添加任務到隊列中,就可以執(zhí)行任務
????dispatch_async(queue, ^{
???????NSLog(@"下載圖片1----%@",[NSThread?currentThread]);
???????});
????dispatch_async(queue, ^{
???????NSLog(@"下載圖片2----%@",[NSThread?currentThread]);
???????????});
????dispatch_async(queue, ^{
???????NSLog(@"下載圖片3----%@",[NSThread?currentThread]);
????????});
?? ?//打印主線程
????NSLog(@"主線程----%@",[NSThread?mainThread]);
}

總結:異步并發(fā)執(zhí)行3個任務,會開啟3個子線程。
2、用異步函數(shù)往串行隊列中添加任務
//異步串行
-(void)ybcx{
????//創(chuàng)建一個隊列,queneName不要加@,這里用c寫法
????dispatch_queue_t queue =? dispatch_queue_create("queneName",?NULL);
????//2.添加任務到隊列中,就可以執(zhí)行任務
????dispatch_async(queue, ^{
????????NSLog(@"下載圖片1----%@",[NSThread?currentThread]);
????});
????dispatch_async(queue, ^{
????????NSLog(@"下載圖片2----%@",[NSThread?currentThread]);
????});
????dispatch_async(queue, ^{
????????NSLog(@"下載圖片3----%@",[NSThread?currentThread]);
????});
????//打印主線程
????NSLog(@"主線程----%@",[NSThread?mainThread]);
}

總結:異步串行執(zhí)行3個任務,只會開啟一個子線程。
3、用同步函數(shù)往并發(fā)隊列中添加任務
//同步并發(fā)
-(void)tbbf{
????//獲取全局并發(fā)隊列
????dispatch_queue_t queue =? dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
????//2.添加任務到隊列中,就可以執(zhí)行任務
????dispatch_sync(queue, ^{
????????NSLog(@"下載圖片1----%@",[NSThread?currentThread]);
????});
????dispatch_sync(queue, ^{
????????NSLog(@"下載圖片2----%@",[NSThread?currentThread]);
????});
????dispatch_sync(queue, ^{
????????NSLog(@"下載圖片3----%@",[NSThread?currentThread]);
????});
????//打印主線程
????NSLog(@"主線程----%@",[NSThread?mainThread]);
}

總結:不會開啟新的線程,并發(fā)隊列失去了并發(fā)的功能。
4、用同步函數(shù)往串行隊列中添加任務
//同步串行
-(void)tbcx{
????//創(chuàng)建一個隊列,queneName不要加@,這里用c寫法
????dispatch_queue_t queue =? dispatch_queue_create("queneName",?NULL);
????//2.添加任務到隊列中,就可以執(zhí)行任務
????dispatch_sync(queue, ^{
????????NSLog(@"下載圖片1----%@",[NSThread?currentThread]);
????});
????dispatch_sync(queue, ^{
????????NSLog(@"下載圖片2----%@",[NSThread?currentThread]);
????});
????dispatch_sync(queue, ^{
????????NSLog(@"下載圖片3----%@",[NSThread?currentThread]);
????});
????//打印主線程
????NSLog(@"主線程----%@",[NSThread?mainThread]);
}

總結:不會開啟新的線程,創(chuàng)建的自定義隊列無效。