之前專案裡用到異步的地方基本都是依賴第三方庫,反而沒有認真系統地練過 iOS 原生多執行緒。其實這塊知識非常重要——有操作系統基礎的同學會發現, concepts 幾乎可以一一對應。本文用一個圖片下載 Demo,把三種主流方案擺在一起對比,並示範執行緒同步鎖的用法。
最終執行效果如下,功能覆蓋得比較完整:

功能清單:
1. 點擊「同步請求圖片」,觀察 UI 是否卡死,並點擊測試按鈕看紅色 Label 能否變成綠色;
2. NSThread 按鈕:用 NSThread 建立執行緒並執行下載;
3. Block 操作與 Invocation 操作:用 NSOperation 的兩種形態提交任務;
4. serial/concurrent:分別對應 GCD 的串行隊列與並行隊列。
不管用純程式碼還是 Storyboard/xib,先把界面控件初始化好。測試按鈕用來切換 Label 背景色,方便肉眼判斷主執行緒是否被阻塞:
// 改變 label 顏色,在紅綠之間切換
- (IBAction)tapTestButton:(id)sender {
static int i = 1;
if (i == 1) {
_testLabel.backgroundColor = [UIColor redColor];
i = 0;
} else {
_testLabel.backgroundColor = [UIColor greenColor];
i = 1;
}
}
下載圖片的方法。這裡刻意加入 sleep 模擬耗時,並列印當前執行緒:
-(NSData *)getImageData {
_count++;
int count = _count; // 線程開始啟動
NSString *str = [NSString stringWithFormat:@"%d.線程%@", count, [NSThread currentThread]];
NSLog(@"%@", str);
NSData *data;
[NSThread sleepForTimeInterval:0.5];
data = [NSData dataWithContentsOfURL:[NSURL URLWithString:IMAGEURL]];
str = [NSString stringWithFormat:@"%d.線程%@完畢", count, [NSThread currentThread]];
// 請求由其他線程完成,UI 更新必須回到主線程
[self performSelectorOnMainThread:@selector(updateTextViewWithString:)
withObject:str waitUntilDone:YES];
return data;
}
日誌刷新與圖片刷新都必須在主執行緒執行:
// 在控制器上顯示圖片請求情況
-(void)updateTextViewWithString:(NSString *)str {
NSString *oldStr = [NSString stringWithFormat:@"%@\n%@", _logTextView.text, str];
_logTextView.text = oldStr;
[self tapTestButton:nil]; // 順便切換 Label 顏色,便於觀察
}
// 更新圖片
-(void)updateImageWithData:(NSData *)data {
UIImage *image = [UIImage imageWithData:data];
[_testImage setImage:image];
}
// 由其他線程請求數據,回主線程更新 UI
-(void)loadImageWithThreadName:(NSString *)threadName {
[[NSThread currentThread] setName:threadName;
NSData *data = [self getImageData];
[self performSelectorOnMainThread:@selector(updateImageWithData:)
withObject:data waitUntilDone:YES];
}
// 同步請求圖片,視圖會阻塞,因為主線程被佔用
- (IBAction)tapButton:(id)sender {
NSData *data = [self getImageData];
[self updateImageWithData:data];
}
請求與 UI 更新都在主線程順序執行,下載期間界面完全凍結,測試按鈕點不動——這就是為什麼網絡請求絕不能放在主線程。
- (IBAction)tapButton2:(id)sender {
// 點一次按鈕就建立 10 個新線程
for (int i = 0; i < 10; i++) {
[NSThread detachNewThreadSelector:@selector(loadImageWithThreadName:)
toTarget:self withObject:@"NSThread"];
}
}
detachNewThreadSelector: 建立的線程會自動啟動,無需手動呼叫 start。優點是直接、直觀;缺點是需要自行管理線程生命週期與數量。
- (IBAction)tapInvocationOperation:(id)sender {
// 調用操作需要放到隊列中才會執行
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
for (int i = 0; i < 10; i++) {
NSInvocationOperation *invocationOperation =
[[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(loadImageWithThreadName:)
object:@"Invocation"];
[operationQueue addOperation:invocationOperation];
}
}
- (IBAction)tapBlockOperation:(id)sender {
__weak __block ViewController *copySelf = self;
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
[copySelf loadImageWithThreadName:@"Block"];
}];
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue addOperation:blockOperation];
for (int i = 0; i < 10; i++) {
// 另一種寫法
[operationQueue addOperationWithBlock:^{
[copySelf loadImageWithThreadName:@"Block"];
}];
}
}
NSOperationQueue 的價值在於它替你管好了執行緒:可以設定 maxConcurrentOperationCount 控制併發數,還支援依賴(addDependency:)與取消,這是裸 NSThread 做不到的。
- (IBAction)tapGCDserialQueue:(id)sender {
dispatch_queue_t serialQueue = dispatch_queue_create("mySerialQueue", DISPATCH_QUEUE_SERIAL);
__weak __block ViewController *copySelf = self;
for (int i = 0; i < 10; i++) {
dispatch_async(serialQueue, ^{
[copySelf loadImageWithThreadName:@"Serial"];
});
}
}
- (IBAction)tapGCDConcurrentQueue:(id)sender {
dispatch_queue_t concurrentQueue =
dispatch_queue_create("myConcurrentQueue", DISPATCH_QUEUE_CONCURRENT);
__weak __block ViewController *copySelf = self;
for (int i = 0; i < 10; i++) {
dispatch_async(concurrentQueue, ^{
[copySelf loadImageWithThreadName:@"Concurrent"];
});
}
}
執行結果:


操作系統課程裡有個經典名詞叫髒數據:多個執行緒同時讀寫同一塊資源,導致數據不一致。我們可以主動製造這個問題。
getImageData 中原本有連續兩句:
_count++; int count = _count;
在中間插入一個延遲:
_count++; [NSThread sleepForTimeInterval:1]; int count = _count;
此時執行會出現大量重複標號——_count 是成員變數,多個執行緒同時對它自增,排程切換導致計數錯亂。
[_lock lock]; _count++; [NSThread sleepForTimeInterval:1]; int count = _count; [_lock unlock];
int count;
@synchronized (self) {
_count++;
[NSThread sleepForTimeInterval:1];
count = _count;
}
兩種方式都能解決問題。@synchronized 寫法更簡潔,本質上也是互斥鎖;NSLock 則更靈活,可配合 tryLock、設定超時等進階用法。

GCD 串行隊列:所有任務在同一條線程上按 FIFO 順序執行,天然免鎖。

GCD 並行隊列:任務分散在不同線程上同時執行,共享資源時仍需自行加鎖。

NSThread 適合簡單、少量的後台任務,程式碼直觀但缺乏調度能力;NSOperationQueue 面向對象化程度高,支援併發數控制、任務依賴與取消,適合業務邏輯相對複雜的場景;GCD 最貼近底層,效能表現好,配合 group、barrier、semaphore 能實現非常精細的控制,是目前 iOS 開發的主流選擇。
無論選哪一種,兩條鐵律不變:UI 更新必須回主線程;共享資源必須保護。