代碼分析上面的四個概念:
#pragma mark - 1異步並發
- (void)asyncGlobal {
// 取得全局並發隊列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 使用異步調用
dispatch_async(queue, ^{
NSLog(@"result1, %@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"result2, %@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"result3, %@",[NSThread currentThread]);
});
}
#pragma mark - 2異步串行
- (void)asyncSerial {
// 創建串行隊列
dispatch_queue_t queue = dispatch_queue_create("Serial", NULL);
// 使用異步調用
dispatch_async(queue, ^{
NSLog(@"result1, %@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"result2, %@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"result3, %@",[NSThread currentThread]);
});
}
#pragma mark - 3同步並發
- (void)syncGlobal {
// 取得全局並發隊列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 使用同步調用
dispatch_sync(queue, ^{
NSLog(@"result1, %@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"result2, %@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"result3, %@",[NSThread currentThread]);
});
}
#pragma mark - 4同步串行
- (void)syncSerial {
// 創建串行隊列
dispatch_queue_t queue = dispatch_queue_create("Serial", NULL);
// 使用同步調用
dispatch_sync(queue, ^{
NSLog(@"result1, %@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"result2, %@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"result3, %@",[NSThread currentThread]);
});
}
上面的代碼,我們可以通過觀察打印線程信息 [NSThread currentThread] 來判斷是否有開啟新的線程及開啟新的線程的情況。上面的執行結果,可以用下面的圖表來描述:
同步 (sync) 不開起新的線程
並發隊列: 不開起新的線程(用默認的主線程)
串行隊列: 不開起新的線程(用默認的主線程)
異步 (async) 開啟新的線程
並發隊列: 能開啟多條線程(取出隊列中的任務,子線程執行;接著取出隊列中後面的任務,開辟其他線程執行這條任務....)
串行隊列: 只開啟一條子線程(取出隊列中的任務,子線程執行,執行完畢後,繼續取出任務,子線程繼續執行....)
4.線程間通信示例 從子線程回到主線程dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//執行耗時的異步操作...
dispatch_async(dispatch_get_main_queue(),^{
// 回到主線程,執行UI刷新操作
});
});
上面的代碼片段是經典的線程間通信使用方法。
Example:
從網絡下載圖片資源,並顯示到主線程UI上面
5. 隊列組
有這麼一種需求 首先:分別異步執行兩個耗時的操作 其次:等兩個異步操作都執行完畢後,再回到主線程執行操作6. GCD其他好用的方法