多線程編程1,c多線程編程
每個iOS應用程式都有個專門用來更新顯示UI介面、處理使用者的觸摸事件的主線程,因此不能將其他太耗時的操作放在主線程中執行,不然會造成主線程堵塞(出現卡機現象),帶來極壞的使用者體驗。一般的解決方案就是將那些耗時的操作放到另外一個線程中去執行,多線程編程是防止主線程堵塞,增加運行效率的最佳方法
iOS支援多個層次的多線程編程,層次越高的抽象程度越高,使用也越方便,也是蘋果最推薦使用的方法。下面根據抽象層次從低到高依次列出iOS所支援的多線程編程方法:
1.Thread :是三種方法裡面相對輕量級的,但需要管理線程的生命週期、同步、加鎖問題,這會導致一定的效能開銷
2.Cocoa Operations:是基於OC實現的,NSOperation以物件導向的方式封裝了需要執行的操作,不必關心線程管理、同步等問題。NSOperation是一個抽象基類,iOS提供了兩種預設實現:NSInvocationOperation和NSBlockOperation,當然也可以自訂NSOperation
3.Grand Central Dispatch(簡稱GCD,iOS4才開始支援):提供了一些新特性、運行庫來支援多核並行編程,它的關注點更高:如何在多個cpu上提升效率
這篇文章簡單介紹了第一種多線程編程的方式,主要是利用NSThread這個類,一個NSThread執行個體代表著一條線程
一、NSthread的初始化
1.動態方法
[java] view plain copy
- - (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
[java] view plain copy
- // 初始化線程
- 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.靜態方法
[java] view plain copy
- + (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
[java] view plain copy
- [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
- // 調用完畢後,會馬上建立並開啟新線程
3.隱式建立線程的方法
[java] view plain copy
- [self performSelectorInBackground:@selector(run) withObject:nil];
二、擷取當前線程
[java] view plain copy
- NSThread *current = [NSThread currentThread];
三、擷取主線程
[java] view plain copy
- NSThread *main = [NSThread mainThread];
四、暫停當前線程
[java] view plain copy
- // 暫停2s
- [NSThread sleepForTimeInterval:2];
-
- // 或者
- NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];
- [NSThread sleepUntilDate:date];
五、線程間的通訊
1.在指定線程上執行操作
[java] view plain copy
- [self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];
2.在主線程上執行操作
[java] view plain copy
- [self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
3.在當前線程執行操作
[java] view plain copy
- [self performSelector:@selector(run) withObject:nil];
六、優缺點
1.優點:NSThread比其他兩種多線程方案較輕量級,更直觀地控制線程對象
2.缺點:需要自己管理線程的生命週期,線程同步。線程同步對資料的加鎖會有一定的系統開銷
文章出處:http://blog.csdn.net/q199109106q/article/details/8566222