Objective-C 的多線程模型簡潔強大,媲美 Java。本文從四大核心維度系統梳理 iOS 多線程開發要點。
// 初始化
NSThread *thread = [[NSThread alloc] initWithTarget:self
selector:@selector(run)
object:nil];
thread.name = @"WorkerThread";
// 手動啟動
[thread start];
[NSThread detachNewThreadSelector:@selector(run)
toTarget:self
withObject:nil];
// GCD 全局佇列
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 後台任務
dispatch_async(dispatch_get_main_queue(), ^{
// 主線程 UI 更新
});
});
// OperationQueue
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
// 後台任務
}];
@interface TicketSeller : NSObject
@property (nonatomic, strong) NSCondition *lock;
@property (nonatomic, assign) int tickets;
- (void)sellTickets;
@end
@implementation TicketSeller
- (void)sellTickets {
[self.lock lock];
while (self.tickets > 0) {
[NSThread sleepForTimeInterval:0.5];
NSLog(@"%@ 售出第 %d 張票,剩餘 %d", [NSThread currentThread].name, 100 - self.tickets + 1, self.tickets - 1);
self.tickets--;
}
[self.lock unlock];
}
@end
@synchronized(self) { ... }:隱式互斥鎖,適合簡單臨界區。NSLock / NSRecursiveLock:基礎鎖對象。dispatch_semaphore_t:信號量,適合資源池控制。OS_UNFAIR_LOCK / pthread_mutex:高效能底層鎖。[self performSelectorOnMainThread:@selector(updateUI:)
withObject:data
waitUntilDone:NO];
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_group_async(group, queue, ^{ /* 任務1 */ });
dispatch_group_async(group, queue, ^{ /* 任務2 */ });
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// 所有任務完成
});
- (void)backgroundTask {
@autoreleasepool {
// 耗時操作
[self performSelectorOnMainThread:@selector(done) withObject:nil waitUntilDone:NO];
}
}
⚠️ 子線程使用 autorelease 必須自建 @autoreleasepool,否則崩潰:NSAutoreleaseNoPool()。
queue.maxConcurrentOperationCount = 4;[op2 addDependency:op1];op.queuePriority = NSOperationQueuePriorityHigh;[queue cancelAllOperations] / [queue setSuspended:YES]isExecuting、isFinished、isCancelled@autoreleasepool 釋放臨時對象。多線程的本質是「共享狀態的協作」,設計清晰的數據流向比鎖技巧更重要。