用異步函數(shù)往并發(fā)隊列中添加任務(wù)
//1、獲得全局的并發(fā)隊列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//2、添加任務(wù)到隊列中,就可以執(zhí)行任務(wù)了
//異步函數(shù):具備開啟線程的能力
dispatch_async(queue, ^{
NSLog(@"下載圖片1-----%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"下載圖片2-----%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"下載圖片3-----%@",[NSThread currentThread]);
});
NSLog(@"主線程----%@",[NSThread mainThread]);
- 打印信息分析得出結(jié)論:同時開啟了三個線程

1.png
用異步函數(shù)往串行隊列中添加任務(wù)
NSLog(@"主線程-----%@",[NSThread mainThread]);
// 1、創(chuàng)建串行隊列
/*
* 第一個參數(shù)是串行隊列的名稱,是C語言字符串
* 第二個參數(shù)是隊列的屬性,一般來說串行隊列不需要賦值任何屬性,所以通常傳NULL
*/
dispatch_queue_t queue = dispatch_queue_create("JHQueue", NULL);
// 2、添加任務(wù)到隊列中
dispatch_async(queue, ^{
NSLog(@"下載圖片1-----%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"下載圖片2-----%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"下載圖片3-----%@",[NSThread currentThread]);
});
// 如果是MRC環(huán)境你需要再寫一行代碼:
// dispatch_release(queue);
- 打印信息分析得出結(jié)論:會開啟線程,但是只開啟一個線程

2.png
用同步函數(shù)往并發(fā)隊列中添加任務(wù)
//打印主線程
NSLog(@"主線程----%@",[NSThread mainThread]);
//創(chuàng)建串行隊列
dispatch_queue_t queue= dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//2.添加任務(wù)到隊列中執(zhí)行
dispatch_sync(queue, ^{
NSLog(@"下載圖片1----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"下載圖片2----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"下載圖片3----%@",[NSThread currentThread]);
});
- 打印信息分析得出結(jié)論:不會開啟新的線程,并發(fā)隊列失去了并發(fā)的功能

3.png
用同步函數(shù)往串行隊列中添加任務(wù)
NSLog(@"主線程-----%@",[NSThread mainThread]);
// 1、創(chuàng)建串行隊列
/*
* 第一個參數(shù)是串行隊列的名稱,是C語言字符串
* 第二個參數(shù)是隊列的屬性,一般來說串行隊列不需要賦值任何屬性,所以通常傳NULL
*/
dispatch_queue_t queue = dispatch_queue_create("JHQueue", NULL);
// 2、添加任務(wù)到隊列中
dispatch_sync(queue, ^{
NSLog(@"下載圖片1-----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"下載圖片2-----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"下載圖片3-----%@",[NSThread currentThread]);
});
- 打印信息分析得出結(jié)論:不會開啟新的線程

4.png
補(bǔ)充點小知識:
1、隊列名稱的作用:將來調(diào)試的時候,可以看得出任務(wù)是在哪個隊列中執(zhí)行的。

5.png
2、同步函數(shù)不具備開啟線程的能力,無論是什么隊列都不會開啟線程;異步函數(shù)具備開啟線程的能力,開啟幾條線程由隊列決定(串行隊列只會開啟一條新的線程,并發(fā)隊列會開啟多條線程)。
- 同步函數(shù)
(1)并發(fā)隊列:不會開線程
(2)串行隊列:不會開線程 - 異步函數(shù)
(1)并發(fā)隊列:能開啟N條線程
(2)串行隊列:開啟1條線程
注意:
凡是函數(shù)中,各種函數(shù)名中帶有create\copy\new\retain等字眼,都需要在不需要使用這個數(shù)據(jù)的時候進(jìn)行release。
GCD的數(shù)據(jù)類型在ARC的環(huán)境下不需要再做release。
CF(core Foundation)的數(shù)據(jù)類型在ARC環(huán)境下還是需要做release。
異步函數(shù)具備開線程的能力,但不一定會開線程。