用異步函數(shù)往并發(fā)隊(duì)列中添加任務(wù)
//1宿礁、獲得全局的并發(fā)隊(duì)列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//2漆腌、添加任務(wù)到隊(duì)列中催蝗,就可以執(zhí)行任務(wù)了
//異步函數(shù):具備開(kāi)啟線程的能力
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é)論:同時(shí)開(kāi)啟了三個(gè)線程
用異步函數(shù)往串行隊(duì)列中添加任務(wù)
NSLog(@"主線程-----%@",[NSThread mainThread]);
// 1、創(chuàng)建串行隊(duì)列
/*
* 第一個(gè)參數(shù)是串行隊(duì)列的名稱导而,是C語(yǔ)言字符串
* 第二個(gè)參數(shù)是隊(duì)列的屬性,一般來(lái)說(shuō)串行隊(duì)列不需要賦值任何屬性,所以通常傳NULL
*/
dispatch_queue_t queue = dispatch_queue_create("JHQueue", NULL);
// 2退渗、添加任務(wù)到隊(duì)列中
dispatch_async(queue, ^{
NSLog(@"下載圖片1-----%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"下載圖片2-----%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"下載圖片3-----%@",[NSThread currentThread]);
});
// 如果是MRC環(huán)境你需要再寫(xiě)一行代碼:
// dispatch_release(queue);
- 打印信息分析得出結(jié)論:會(huì)開(kāi)啟線程,但是只開(kāi)啟一個(gè)線程
用同步函數(shù)往并發(fā)隊(duì)列中添加任務(wù)
//打印主線程
NSLog(@"主線程----%@",[NSThread mainThread]);
//創(chuàng)建串行隊(duì)列
dispatch_queue_t queue= dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//2.添加任務(wù)到隊(duì)列中執(zhí)行
dispatch_sync(queue, ^{
NSLog(@"下載圖片1----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"下載圖片2----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"下載圖片3----%@",[NSThread currentThread]);
});
- 打印信息分析得出結(jié)論:不會(huì)開(kāi)啟新的線程蕴纳,并發(fā)隊(duì)列失去了并發(fā)的功能
用同步函數(shù)往串行隊(duì)列中添加任務(wù)
NSLog(@"主線程-----%@",[NSThread mainThread]);
// 1会油、創(chuàng)建串行隊(duì)列
/*
* 第一個(gè)參數(shù)是串行隊(duì)列的名稱,是C語(yǔ)言字符串
* 第二個(gè)參數(shù)是隊(duì)列的屬性古毛,一般來(lái)說(shuō)串行隊(duì)列不需要賦值任何屬性翻翩,所以通常傳NULL
*/
dispatch_queue_t queue = dispatch_queue_create("JHQueue", NULL);
// 2、添加任務(wù)到隊(duì)列中
dispatch_sync(queue, ^{
NSLog(@"下載圖片1-----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"下載圖片2-----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"下載圖片3-----%@",[NSThread currentThread]);
});
- 打印信息分析得出結(jié)論:不會(huì)開(kāi)啟新的線程
補(bǔ)充點(diǎn)小知識(shí):
1稻薇、隊(duì)列名稱的作用:將來(lái)調(diào)試的時(shí)候嫂冻,可以看得出任務(wù)是在哪個(gè)隊(duì)列中執(zhí)行的。
2塞椎、同步函數(shù)不具備開(kāi)啟線程的能力桨仿,無(wú)論是什么隊(duì)列都不會(huì)開(kāi)啟線程;異步函數(shù)具備開(kāi)啟線程的能力案狠,開(kāi)啟幾條線程由隊(duì)列決定(串行隊(duì)列只會(huì)開(kāi)啟一條新的線程服傍,并發(fā)隊(duì)列會(huì)開(kāi)啟多條線程)钱雷。
- 同步函數(shù)
(1)并發(fā)隊(duì)列:不會(huì)開(kāi)線程
(2)串行隊(duì)列:不會(huì)開(kāi)線程 - 異步函數(shù)
(1)并發(fā)隊(duì)列:能開(kāi)啟N條線程
(2)串行隊(duì)列:開(kāi)啟1條線程
注意:
凡是函數(shù)中,各種函數(shù)名中帶有create\copy\new\retain等字眼吹零,都需要在不需要使用這個(gè)數(shù)據(jù)的時(shí)候進(jìn)行release罩抗。
GCD的數(shù)據(jù)類型在ARC的環(huán)境下不需要再做release。
CF(core Foundation)的數(shù)據(jù)類型在ARC環(huán)境下還是需要做release灿椅。
異步函數(shù)具備開(kāi)線程的能力套蒂,但不一定會(huì)開(kāi)線程。