前言
每個iOS應(yīng)用程序都有個專門用來更新顯示UI界面、處理用戶觸摸事件的主線程,因此不能將其他太耗時的操作放在主線程中執(zhí)行,不然會造成主線程堵塞(出現(xiàn)卡機(jī)現(xiàn)象),帶來極壞的用戶體驗(yàn)。一般的解決方案就是將那些耗時的操作放到另外一個線程中去執(zhí)行,多線程編程是防止主線程堵塞,增加運(yùn)行效率的最佳方法。
iOS中有3種常見的多線程編程方法:
1.NSThread
這種方法需要管理線程的生命周期、同步、加鎖問題,會導(dǎo)致一定的性能開銷
2.NSOperation和NSOperationQueue
是基于OC實(shí)現(xiàn)的。NSOperation以面向?qū)ο蟮姆绞椒庋b了需要執(zhí)行的操作,然后可以將這個操作放到一個NSOperationQueue中去異步執(zhí)行。不必關(guān)心線程管理、同步等問題。
3.Grand Centeral Dispatch
簡稱GCD,iOS4才開始支持,是純C語言的API。自iPad2開始,蘋果設(shè)備開始有了雙核CPU,為了充分利用這2個核,GCD提供了一些新特性來支持多核并行編程
這篇文章簡單介紹NSThread這個類,一個NSThread實(shí)例就代表著一條線程
一、獲取當(dāng)前線程
NSThread *current = [NSThreadcurrentThread];
二、獲取主線程
1NSThread *main =[NSThreadmainThread];2NSLog(@"主線程:%@", main);
打印結(jié)果是:
2013-04-1821:36:38.599thread[7499:c07] 主線程:{name = (null), num =1}
num相當(dāng)于線程的id,主線程的num是為1的
三、NSThread的創(chuàng)建
1.動態(tài)方法
- (id)initWithTarget:(id)target selector:(SEL)selectorobject:(id)argument;
* 在第2行創(chuàng)建了一條新線程,然后在第4行調(diào)用start方法啟動線程,線程啟動后會調(diào)用self的run:方法,并且將@"mj"作為方法參數(shù)
1// 初始化線程2NSThread *thread = [[[NSThread alloc] initWithTarget:self selector:@selector(run:)object:@"mj"] autorelease];3// 開啟線程4[thread start];
假如run:方法是這樣的:
1- (void)run:(NSString *)string {2NSThread *current = [NSThread currentThread];3NSLog(@"執(zhí)行了run:方法-參數(shù):%@,當(dāng)前線程:%@",string, current);4}
打印結(jié)果為:
2013-04-1821:40:33.102thread[7542:3e13] 執(zhí)行了run:方法-參數(shù):mj,當(dāng)前線程:{name = (null), num =3}
可以發(fā)現(xiàn),這條線程的num值為3,說明不是主線程,主線程的num為1
2.靜態(tài)方法
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"mj"];
執(zhí)行完上面代碼后會馬上啟動一條新線程,并且在這條線程上調(diào)用self的run:方法,以@"mj"為方法參數(shù)
3.隱式創(chuàng)建線程
[self performSelectorInBackground:@selector(run:) withObject:@"mj"];
會隱式地創(chuàng)建一條新線程,并且在這條線程上調(diào)用self的run:方法,以@"mj"為方法參數(shù)
四、暫停當(dāng)前線程
[NSThreadsleepForTimeInterval:2];
NSDate *date = [NSDate dateWithTimeInterval:2sinceDate:[NSDate date]];? [NSThreadsleepUntilDate:date];
上面兩種做法都是暫停當(dāng)前線程2秒
五、線程的其他操作
1.在指定線程上執(zhí)行操作
1[selfperformSelector:@selector(run)onThread:threadwithObject:nilwaitUntilDone:YES];
* 上面代碼的意思是在thread這條線程上調(diào)用self的run方法
* 最后的YES代表:上面的代碼會阻塞,等run方法在thread線程執(zhí)行完畢后,上面的代碼才會通過
2.在主線程上執(zhí)行操作
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
在主線程調(diào)用self的run方法
3.在當(dāng)前線程執(zhí)行操作
[self performSelector:@selector(run) withObject:nil];
在當(dāng)前線程調(diào)用self的run方法
六、優(yōu)缺點(diǎn)
1.優(yōu)點(diǎn):NSThread比其他多線程方案較輕量級,更直觀地控制線程對象
2.缺點(diǎn):需要自己管理線程的生命周期,線程同步。線程同步對數(shù)據(jù)的加鎖會有一定的系統(tǒng)開銷