今天咱們講解幾道這兩天遇到的面試題--GCD編程的.題目很不錯,很考究關於GCD的基本概念和使用.html
對於基本的概念,本人博客已在前面講過,本篇主要以面試題來說解.你們可看一下本人關於GCD的基本講解 http://www.javashuo.com/article/p-qldrphhv-gy.html面試
GCD編程的核心就是dispatch隊列, dispatch block的執行都會最終放到某個隊列中執行.咱們直接以題目來說解:編程
【例1】GCD面試題1xcode
- (void)viewDidLoad { [super viewDidLoad]; [self testGCD]; } - (void)testGCD { //並行隊列 dispatch_queue_t queue = dispatch_queue_create("zxy", DISPATCH_QUEUE_CONCURRENT); NSLog(@"1"); dispatch_async(queue, ^{ NSLog(@"2"); dispatch_async(queue, ^{ NSLog(@"3"); }); NSLog(@"4"); }); NSLog(@"5"); }
講解:異步
NSLog(@"2"); dispatch_async(queue, ^{ NSLog(@"3"); }); NSLog(@"4");
驗證結果截圖:async
【例2】GCD面試題2spa
- (void)viewDidLoad { [super viewDidLoad]; [self testGCD]; } - (void)testGCD { //串行隊列 dispatch_queue_t queue = dispatch_queue_create("zxy", DISPATCH_QUEUE_SERIAL); NSLog(@"1"); dispatch_async(queue, ^{ NSLog(@"2"); dispatch_sync(queue, ^{ NSLog(@"3"); }); NSLog(@"4"); }); NSLog(@"5"); }
講解:線程
驗證結果截圖:3d
【例3】GCD面試題3code
dispatch_queue_t queue = dispatch_queue_create("zxy", DISPATCH_QUEUE_CONCURRENT); dispatch_async(queue, ^{ NSLog(@"哈哈哈 1"); }); dispatch_async(queue, ^{ NSLog(@"哈哈哈 2"); }); dispatch_sync(queue, ^{ NSLog(@"哈哈哈 3"); });
//////////////////// NSLog(@"哈哈哈 0"); dispatch_async(queue, ^{ NSLog(@"哈哈哈 7"); }); dispatch_async(queue, ^{ NSLog(@"哈哈哈 8"); }); dispatch_async(queue, ^{ NSLog(@"哈哈哈 9"); });
A 1230789 B 1237890 C 3120798 D 2137890 C 3012789
上面五種答案,哪個是對的?
講解:
將上面的代碼運行到xcode獲得以下:E答案
【例4】GCD面試題4
咱們將DISPATCH_QUEUE_CONCURRENT改成DISPATCH_QUEUE_SERIAL
由於將並行隊列改成串行隊列,全部任務循序漸進執行,因此結果以下(不加以講解)
【例5】GCD面試題5
- (void) testGCD{ __block NSInteger a = 0; while (a < 100) { dispatch_async(dispatch_get_global_queue(0, 0), ^{ a++; NSLog(@"%ld======%@", a, [NSThread currentThread]); }); } NSLog(@"臥槽無情%ld", a); }
講解:
可能狀態還不錯,從上面看出結果爲100
拓展 下面有幾道一樣的相似GCD面試題目,結果給你們,你們本身體會
【例6】GCD面試題6
- (void) testGCD2 { dispatch_queue_t queue = dispatch_queue_create("zxy", DISPATCH_QUEUE_CONCURRENT); NSLog(@"1"); dispatch_async(queue, ^{ NSLog(@"2"); dispatch_sync(queue, ^{ NSLog(@"3"); }); NSLog(@"4"); }); NSLog(@"5"); }
結果以下:
【例7】GCD面試題7
- (void) testGCD2 { dispatch_queue_t queue = dispatch_queue_create("zxy", DISPATCH_QUEUE_CONCURRENT); NSLog(@"1"); dispatch_async(queue, ^{ NSLog(@"2"); dispatch_async(queue, ^{ NSLog(@"3"); }); NSLog(@"4"); }); NSLog(@"5"); }
結果以下:
【例8】GCD面試題8
- (void) testGCD2 { dispatch_queue_t queue = dispatch_queue_create("zxy", DISPATCH_QUEUE_SERIAL); NSLog(@"1"); dispatch_async(queue, ^{ NSLog(@"2"); dispatch_async(queue, ^{ NSLog(@"3"); }); NSLog(@"4"); }); NSLog(@"5"); }
結果以下:
以上就是GCD的經典面試題,其實看了這幾道面試題,發現還都是GCD的基本內容,串行隊列,並行隊列,以及同步異步是否開啓線程的基本概念,但願經過本次講解,你們對GCD的認識會更上一層,謝謝!!!