dispatch_set_target_queue
利用dispatch_queue_create生成的函數的優先級都是'默認優先級'。但是想要改變優先級就需要用到這個函數:dispatch_set_target_queue。dispatch_set_target_queue不僅可以改變優先級,還可以改變執行層次.
dispatch_queue_t serialQueue = dispatch_queue_create("com.test", NULL);
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
// serial的優先級 == globalQueue的優先級
dispatch_set_target_queue(serial, globalQueue);
解決多個Serial Dispatch Queue并行執行
當一個任務被分為ABCD的時候,還需要他們串行執行,就需要dispatch_set_target_queue來幫助實現.如下:
dispatch_queue_t serialQueue = dispatch_queue_create("com.test", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t serialQueue2 = dispatch_queue_create("com.test2", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t serialQueue3 = dispatch_queue_create("com.test3", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t serialQueue4 = dispatch_queue_create("com.test4", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t serialQueue5 = dispatch_queue_create("com.test5", DISPATCH_QUEUE_SERIAL);
dispatch_set_target_queue(serialQueue2, serialQueue);
dispatch_set_target_queue(serialQueue3, serialQueue);
dispatch_set_target_queue(serialQueue4, serialQueue);
dispatch_set_target_queue(serialQueue5, serialQueue);
dispatch_sync(serialQueue2, ^{
NSLog(@"2000000");
[NSThread sleepForTimeInterval:3];
NSLog(@"20000001");
});
dispatch_sync(serialQueue3, ^{
NSLog(@"300000");
[NSThread sleepForTimeInterval:2];
NSLog(@"30000001");
});
dispatch_sync(serialQueue4, ^{
NSLog(@"40000000");
[NSThread sleepForTimeInterval:2.5];
NSLog(@"40000001");
});
dispatch_sync(serialQueue5, ^{
NSLog(@"5000000");
[NSThread sleepForTimeInterval:1];
NSLog(@"50000001");
});
執行結果:
dispatch_after
這個應該夠很熟悉了,使用場景就是,你想在3秒后進行此操作,就可以通過該函數來實現。
??:此處的3秒不是在3秒后執行,而是在3秒后追加Block到Dispatch Queue中。
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 3*NSEC_PER_SEC);
dispatch_after(time, dispatch_get_main_queue(), ^{
NSLog(@"汪汪汪...");
});
Dispatch Group
當多個執行處理完成后我們想執行結束處理,這種情況應該怎么辦呢?
答:就serial dispatch queue 來說,在它的最后追加結束處理即可。但是使用Concurrent Dispatch Queue或者同時使用多個的時候,想要執行結束處理,就會有點難。。。。
嘖嘖嘖!!!我們可以使用Dispatch Group:
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_async(group, queue, ^{NSLog(@"12345");});
dispatch_group_async(group, queue, ^{NSLog(@"1234567");});
dispatch_group_async(group, queue, ^{NSLog(@"123456789");});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"over...");
});
*注意:
無論向什么樣的Dispatch Queue中追加block,'dispatch_group_notify'都會最后(在所有任務處理完成)執行。
執行結果:
2016-07-07 14:16:17.092 多線程之GCD[14481:166110] 12345
2016-07-07 14:16:17.092 多線程之GCD[14481:166139] 123456789
2016-07-07 14:16:17.092 多線程之GCD[14481:166116] 1234567
2016-07-07 14:16:17.433 多線程之GCD[14481:165974] over...