您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 多線程入門:NSThread 用法、線程通信與同步實戰

編輯:iOS 開發綜合

iOS 的多線程方案有三套:GCD、NSOperation、NSThread。前兩者是高層封裝,NSThread 則是最底層、最貼近系統線程的一層。日常開發中 GCD 用得最多,但理解 NSThread 對搞清 RunLoop、線程同步、線程生命周期這些基礎概念很有幫助——很多面試題和线上问题的答案都在這一層。

一、NSThread 是什麼

NSThread 是蘋果提供的輕量級多線程編程接口(相對於 GCD 和 NSOperation 而言)。一個 NSThread 對象對應一條線程,你需要手動管理它的生命周期,也需要自己處理線程同步問題。換句話說,它把控制權更多地交給了你,同時也把責任交給了你。

二、常用方法

1. 動態創建

NSThread *newThread = [[NSThread alloc] initWithTarget:self
                                              selector:@selector(threadRun)
                                                object:nil];

返回一個新的 thread 對象,此時線程尚未啟動,需要顯式調用 start。這種方式的好處是能拿到對象引用,便於後續設置 name、qualityOfService 或取消操作。

2. 靜態創建(自動啟動)

[NSThread detachNewThreadSelector:@selector(threadRun)
                          toTarget:self
                        withObject:nil];

一行代碼完成創建與啟動,但沒有返回值。如果需要在任務里拿到當前線程對象,用 [NSThread currentThread]。

3. 啟動

[newThread start];

4. 暫停(阻塞當前線程)

[NSThread sleepForTimeInterval:1.0];
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];

5. 取消

[newThread cancel];

這裡有個關鍵認知:cancel 不會真正停止線程。它只是把線程的 isCancelled 標志置為 YES,相當於一個「請自行退出」的提示。線程要不要退出,取決於你的任務代碼是否檢查這個標志。

6. 強制停止

[NSThread exit];

這才是真正立即終止。它會結束除主線程外的當前線程,無論任務是否執行完畢。由於可能導致資源未釋放、內存泄漏甚至數據不一致,必須在完全掌握線程狀態的前提下謹慎使用。

7. 獲取線程

[NSThread currentThread];   // 當前線程
[NSThread mainThread];      // 主線程

8. 優先級設置

iOS 8 之前:

[NSThread setThreadPriority:1.0];

這個 API 的問題在於數值含義不明——你根本判斷不出該傳 0.5 還是 0.8 才合適。所以 iOS 8 之後蘋果為 threadPriority 加了 To be deprecated; use qualityOfService below 的註釋,推薦改用 qualityOfService 枚舉:

NSQualityOfServiceUserInteractive      // 最高:直接響應用戶交互,如動畫渲染
NSQualityOfServiceUserInitiated         // 次高:用戶等待的即時任務,如打開文檔
NSQualityOfServiceDefault               // 默認:主線程及未設置優先級的線程
NSQualityOfServiceUtility               // 普通:耗時但可等待,如網絡下載
NSQualityOfServiceBackground            // 最低:用戶察覺不到的任務,如預備份

設置方式:

[newThread setQualityOfService:NSQualityOfServiceUserInitiated];

這個枚舉的價值不只是語義清晰——系統會根據它動態調整 CPU 與 I/O 資源分配,在低端設備上效果尤其明顯。

三、線程間通信

1. 在當前線程執行

[self performSelector:@selector(threadRun)];
[self performSelector:@selector(threadRun) withObject:nil];
[self performSelector:@selector(threadRun) withObject:nil afterDelay:2.0];

2. 指定在主線程執行

[self performSelectorOnMainThread:@selector(threadRun)
                       withObject:nil
                    waitUntilDone:YES];

這是最常用的一種。所有 UI 更新必須在主線程進行,子線程拿到數據後要通過這個方法回主線程刷界面。

3. 指定在某個特定線程執行

[self performSelector:@selector(threadRun)
               onThread:newThread
         withObject:nil
      waitUntilDone:YES];

// 或者開一條後台線程
[self performSelectorInBackground:@selector(threadRun) withObject:nil];

四、線程同步

多條線程可能共享同一份資源。當多個線程同時讀寫這份資源時,就可能產生沖突。線程同步的意思是:在一段時間內,只允許一條線程訪問某項資源。

iOS 中常見的加鎖方式有 NSLock 和 @synchronized 兩種。

五、實戰:模擬多窗口售票

場景設定:某演唱會門票發售,北京和廣州同時開窗銷售,共 50 張票。

1. 先監聽線程退出通知

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(threadExitNotice:)
                                             name:NSThreadWillExitNotification
                                           object:nil];

2. 開兩個子線程

_ticketCount = 50;

NSThread *window1 = [[NSThread alloc] initWithTarget:self
                                            selector:@selector(saleTicket)
                                              object:nil];
window1.name = @"北京售票窗口";
[window1 start];

NSThread *window2 = [[NSThread alloc] initWithTarget:self
                                            selector:@selector(saleTicket)
                                              object:nil];
window2.name = @"廣州售票窗口";
[w
				
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved