建立並啟動線程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; [thread start]; // 線程一啟動,就會在 thread 中執行 self 的 run 方法
主線程相關
+ (NSThread *)mainThread; // 取得主線程 - (BOOL)isMainThread; // 是否為主線程 + (BOOL)isMainThread; // 是否為主線程
取得目前線程與線程名稱
NSThread *current = [NSThread currentThread]; - (void)setName:(NSString *)name; - (NSString *)name;
建立後自動啟動
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
隱式建立並啟動
[self performSelectorInBackground:@selector(run) withObject:nil];
下圖大致描述了線程從建立、就緒、執行到結束的流轉關係:
@synchronized(鎖對象) {
// 需要鎖定的程式碼
}
注意:同一段程式碼只該用一把鎖,用多把鎖是不起作用的。
互斥鎖的優缺點很明確。優點是能有效防止多線程搶奪資源造成的資料安全問題;缺點是需要消耗大量 CPU 資源。使用前提是「多條線程搶奪同一塊資源」。
相關術語是「線程同步」,意思是讓多條線程按順序執行任務,而互斥鎖正是同步技術的一種體現。
OC 宣告屬性時有 nonatomic 與 atomic 兩種選擇。atomic 是原子屬性,會為 setter 方法加鎖(預設即為 atomic);nonatomic 則不加鎖。atomic 的加鎖原理大致如下:
@property (assign, atomic) int age;
- (void)setAge:(int)age {
@synchronized(self) {
_age = age;
}
}
兩者對比:atomic 線程安全但消耗資源較多;nonatomic 非線程安全,效能較好,適合記憶體有限的行動裝置。
iOS 開發的實務建議是:所有屬性都宣告為 nonatomic;盡量避免多線程搶奪同一塊資源;盡量把加鎖與資源競爭的業務邏輯交給伺服器端處理,以減輕客戶端壓力。
在一個進程中,線程很少是孤立存在的,彼此常需要通信。通信的體現有兩種:一條線程把資料傳給另一條線程;或一條線程做完特定任務後,轉到另一條線程繼續執行。
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait; - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
典型場景是圖片下載:在子線程抓圖,回到主線程更新 UI。
業務描述很單純:模擬兩個線程搶奪同一份資源(100 張票)。
1. 屬性與方法宣告
/* 1. NSThread 可以使用 NSLock 進行加鎖 2. NSOperation 與 GCD 則建議使用同步鎖 @synchronized(self),並且把搶奪的資源宣告為 atomic 屬性 */ @property (atomic, assign) int tickets; @property (atomic, strong) NSLock *lock; // 顯示結果的區域 @property (weak, nonatomic) IBOutlet UITextView *messageBoard; // 開始售票 - (IBAction)threadSale;
2. 點擊 Start 對應的方法
- (IBAction)threadSale {
// 先設定票數
_tickets = 100;
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(threadSaleMethod) object:nil];
thread1.name = @"售票線程-1"; // 便於追蹤時知道誰在工作
[thread1 start];
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(threadSaleMethod) object:nil];
thread2.name = @"售票線程-2";
[thread2 start];
}
3. 子線程執行的內容
- (void)threadSaleMethod {
// 鎖的懶加載
if (_lock == nil) {
_lock = [[NSLock alloc] init];
}
while (YES) {
[_lock lock];
if (_tickets > 0) {
NSString *message = [NSString stringWithFormat:@"當前票數是%d,售票線程是%@", _tickets, [[NSThread currentThread] name]];
// 更新 UI 一定要回到主線程
// waitUntilDone 表示是否等待主線程更新完畢
[self performSelectorOnMainThread:@selector(appendTextView:) withObject:message waitUntilDone:YES];
_tickets--;
[_lock unlock];
// 模擬延時,讓兩個線程的節奏不同
if ([[[NSThread currentThread] name] isEqualToString:@"售票線程-1"]) {
[NSThread sleepForTimeInterval:0.2];
} else {
[NSThread sleepForTimeInterval:0.3];
}
} else {
[_lock unlock]; // 退出前也要解鎖
NSString *str = [NSString stringWithFormat:@"票已售完%@", [[NSThread currentThread] name]];
[self performSelectorOnMainThread:@selector(appendTextView:) withObject:str waitUntilDone:YES];
break;
}
}
}
4. 更新主線程 UI
- (void)appendTextView:(NSString *)text {
NSMutableString *str = [NSMutableString stringWithString:self.messageBoard.text];
[str appendFormat:@"\n%@", text];
self.messageBoard.text = str;
// 讓文字框捲到最後:參數是一個 NSRange
NSRange range = NSMakeRange(str.length, 1);
[self.messageBoard scrollRangeToVisible:range];
}
這個範例示範了三件事:如何建立與命名線程、如何用 NSLock 保護共享資源,以及如何把 UI 更新切回主線程。下一節接著談 GCD 的概念與用法。