天天看點

iOS 多線程 NSThread一、NSThread的初始化二、擷取目前線程三、擷取主線程四、暫停目前線程五、線程間的通信六、優缺點

每個iOS應用程式都有個專門用來更新顯示UI界面、處理使用者的觸摸事件的主線程,是以不能将其他太耗時的操作放在主線程中執行,不然會造成主線程堵塞(出現卡機現象),帶來極壞的使用者體驗。一般的解決方案就是将那些耗時的操作放到另外一個線程中去執行,多線程程式設計是防止主線程堵塞,增加運作效率的最佳方法。
           

iOS支援多個層次的多線程程式設計,層次越高的抽象程度越高,使用也越友善,也是蘋果最推薦使用的方法。下面根據抽象層次從低到高依次列出iOS所支援的多線程程式設計方法:

  • 1、Thread :是三種方法裡面相對輕量級的,但需要管理線程的生命周期、同步、加鎖問題,這會導緻一定的性能開銷
  • 2、Cocoa Operations:是基于OC實作的,NSOperation以面向對象的方式封裝了需要執行的操作,不必關心線程管理、同步等問題。NSOperation是一個抽象基類,iOS提供了兩種預設實作:NSInvocationOperation和NSBlockOperation,當然也可以自定義NSOperation
  • 3、Grand Central Dispatch(簡稱GCD,iOS4才開始支援):提供了一些新特性、運作庫來支援多核并行程式設計,它的關注點更高:如何在多個cpu上提升效率

一、NSThread的初始化

1、動态方法

  • -(id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
// 初始化線程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
// 設定線程的優先級(0.0 - 1.0,1.0最進階)
thread.threadPriority = 1;
// 開啟線程
[thread start];
           
參數解析:
selector :線程執行的方法,這個selector最多隻能接收一個參數
target :selector消息發送的對象
argument : 傳給selector的唯一參數,也可以是nil
           

2、靜态方法

  • +(void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
- // 調用完畢後,會馬上建立并開啟新線程
           

3、隐式建立線程的方法

[self performSelectorInBackground:@selector(run) withObject:nil];
           

二、擷取目前線程

NSThread *current = [NSThread currentThread];
           

三、擷取主線程

NSThread *main = [NSThread mainThread];
           

四、暫停目前線程

// 暫停2s
[NSThread sleepForTimeInterval:2];
// 或者
NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];
[NSThread sleepUntilDate:date];
           

五、線程間的通信

1、在指定線程上執行操作

[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];
           

2、在主線程上執行操作

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

3、在目前線程執行操作

[self performSelector:@selector(run) withObject:nil];
           

六、優缺點

1、優點

優點:NSThread比其他兩種多線程方案較輕量級,更直覺地控制線程對象

2、缺點

缺點:需要自己管理線程的生命周期,線程同步。線程同步對資料的加鎖會有一定的系統開銷