//(1)用異步函數往并發隊列中添加任務,//總結:同時開啟三個子線程- (void)test1 { //1.獲得全局的并發隊列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //2.添加任務到隊列中,就可以執行任務 //異步函數:具備開啟新線程的能力 dispatch_async(queue, ^{ NSLog(@"下載圖片1----%@",[NSThread currentThread]); }); dispatch_async(queue, ^{ NSLog(@"下載圖片2----%@",[NSThread currentThread]); }); dispatch_async(queue, ^{ NSLog(@"下載圖片3----%@",[NSThread currentThread]); }); //打印主線程 NSLog(@"主線程----%@",[NSThread mainThread]);}
//(2)用異步函數往串行隊列中添加任務//總結:會開啟線程,但是只開啟一個線程- (void)test2 { //打印主線程 NSLog(@"主線程----%@",[NSThread mainThread]); //創建串行隊列 dispatch_queue_t queue= dispatch_queue_create("tqh", NULL); //第一個參數為串行隊列的名稱,是c語言的字符串 //第二個參數為隊列的屬性,一般來說串行隊列不需要賦值任何屬性,所以通常傳空值(NULL) //2.添加任務到隊列中執行 dispatch_async(queue, ^{ NSLog(@"下載圖片1----%@",[NSThread currentThread]); }); dispatch_async(queue, ^{ NSLog(@"下載圖片2----%@",[NSThread currentThread]); }); dispatch_async(queue, ^{ NSLog(@"下載圖片3----%@",[NSThread currentThread]); }); //3.釋放資源 // dispatch_release(queue);}
//3)用同步函數往并發隊列中添加任務//總結:不會開啟新的線程,并發隊列失去了并發的功能- (void)test3 { //打印主線程 NSLog(@"主線程----%@",[NSThread mainThread]); //創建串行隊列 dispatch_queue_t queue= dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //2.添加任務到隊列中執行 dispatch_sync(queue, ^{ NSLog(@"下載圖片1----%@",[NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"下載圖片2----%@",[NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"下載圖片3----%@",[NSThread currentThread]); });}
//(4)用同步函數往串行隊列中添加任務//總結:不會開啟新的線程- (void)test4 { NSLog(@"用同步函數往串行隊列中添加任務"); //打印主線程 NSLog(@"主線程----%@",[NSThread mainThread]); //創建串行隊列 dispatch_queue_t queue= dispatch_queue_create("tqh", NULL); //2.添加任務到隊列中執行 dispatch_sync(queue, ^{ NSLog(@"下載圖片1----%@",[NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"下載圖片2----%@",[NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"下載圖片3----%@",[NSThread currentThread]); });}
/** 補充:隊列名稱的作用: 將來調試的時候,可以看得出任務是在哪個隊列中執行的。 說明:同步函數不具備開啟線程的能力,無論是什么隊列都不會開啟線程;異步函數具備開啟線程的能力,開啟幾條線程由隊列決定(串行隊列只會開啟一條新的線程,并發隊列會開啟多條線程)。 同步函數 (1)并發隊列:不會開線程 (2)串行隊列:不會開線程 異步函數 (1)并發隊列:能開啟N條線程 (2)串行隊列:開啟1條線程 補充: 凡是函數中,各種函數名中帶有create/copy/new/retain等字眼,都需要在不需要使用這個數據的時候進行release。 GCD的數據類型在ARC的環境下不需要再做release。 CF(core Foundation)的數據類型在ARC環境下還是需要做release。 異步函數具備開線程的能力,但不一定會開線程 */
新聞熱點
疑難解答