每個iOS應(yīng)用程序都有個專門用來更新顯示UI界面娜搂、處理用戶的觸摸事件的主線程漠秋,因此不能將其他太耗時(shí)的操作放在主線程中執(zhí)行懈息,不然會造成主線程堵塞(出現(xiàn)卡機(jī)現(xiàn)象)风范,帶來極壞的用戶體驗(yàn)咨跌。一般的解決方案就是將那些耗時(shí)的操作放到另外一個線程中去執(zhí)行,多線程編程是防止主線程堵塞硼婿,增加運(yùn)行效率的最佳方法
iOS支持多個層次的多線程編程锌半,層次越高的抽象程度越高,使用也越方便寇漫,也是蘋果最推薦使用的方法刊殉。下面根據(jù)抽象層次從低到高依次列出iOS所支持的多線程編程方法:
1.Thread :是三種方法里面相對輕量級的,但需要管理線程的生命周期州胳、同步记焊、加鎖問題,這會導(dǎo)致一定的性能開銷
2.Cocoa Operations:是基于OC實(shí)現(xiàn)的栓撞,NSOperation以面向?qū)ο蟮姆绞椒庋b了需要執(zhí)行的操作遍膜,不必關(guān)心線程管理、同步等問題腐缤。NSOperation是一個抽象基類捌归,iOS提供了兩種默認(rèn)實(shí)現(xiàn):NSInvocationOperation和NSBlockOperation,當(dāng)然也可以自定義NSOperation
3.Grand Central Dispatch(簡稱GCD岭粤,iOS4才開始支持):提供了一些新特性惜索、運(yùn)行庫來支持多核并行編程,它的關(guān)注點(diǎn)更高:如何在多個cpu上提升效率
這篇文章簡單介紹了第一種多線程編程的方式剃浇,主要是利用NSThread這個類巾兆,一個NSThread實(shí)例代表著一條線程
一、NSthread的初始化
1.動態(tài)方法
[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];
// 設(shè)置線程的優(yōu)先級(0.0 - 1.0虎囚,1.0最高級)
thread.threadPriority = 1;
// 開啟線程
[thread start];
參數(shù)解析:
selector :線程執(zhí)行的方法角塑,這個selector最多只能接收一個參數(shù)
target :selector消息發(fā)送的對象
argument : 傳給selector的唯一參數(shù),也可以是nil
2.靜態(tài)方法
[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];
// 調(diào)用完畢后淘讥,會馬上創(chuàng)建并開啟新線程
3.隱式創(chuàng)建線程的方法
[java] view plain copy
[self performSelectorInBackground:@selector(run) withObject:nil];
二圃伶、獲取當(dāng)前線程
[java] view plain copy
NSThread *current = [NSThread currentThread];
三、獲取主線程
[java] view plain copy
NSThread *main = [NSThread mainThread];
四蒲列、暫停當(dāng)前線程
[java] view plain copy
// 暫停2s
[NSThread sleepForTimeInterval:2];
// 或者
NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];
[NSThread sleepUntilDate:date];
五窒朋、線程間的通信
1.在指定線程上執(zhí)行操作
[java] view plain copy
[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];
2.在主線程上執(zhí)行操作
[java] view plain copy
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
3.在當(dāng)前線程執(zhí)行操作
[java] view plain copy
[self performSelector:@selector(run) withObject:nil];
六、優(yōu)缺點(diǎn)
1.優(yōu)點(diǎn):NSThread比其他兩種多線程方案較輕量級蝗岖,更直觀地控制線程對象
2.缺點(diǎn):需要自己管理線程的生命周期侥猩,線程同步。線程同步對數(shù)據(jù)的加鎖會有一定的系統(tǒng)開銷