前言
在日常開(kāi)發(fā)中难菌,多線(xiàn)程的使用能幫助我們解決很多問(wèn)題试溯,比如大量數(shù)據(jù)的運(yùn)算蔑滓,復(fù)雜程序的執(zhí)行,以及利用鎖來(lái)實(shí)現(xiàn)一些需求遇绞,本系列文章主要介紹 iOS 中多線(xiàn)程實(shí)現(xiàn)技術(shù)的用法键袱。
關(guān)于 pthread 的介紹和使用請(qǐng)查看之前的文章,本篇文章針對(duì) NSThread 來(lái)贅述摹闽。
關(guān)于 NSThread
NSThread 是蘋(píng)果官方提供給我們的一種面向?qū)ο蟮妮p量級(jí)多線(xiàn)程解決方案蹄咖,一個(gè) NSThread 對(duì)象代表一個(gè)線(xiàn)程,需要程序員手動(dòng)管理線(xiàn)程的生命周期付鹿,處理線(xiàn)程同步等問(wèn)題澜汤。
NSThread 使用
常用方法
在日常開(kāi)發(fā)中,我們經(jīng)常會(huì)用 [NSThread currentThread]
來(lái)獲取當(dāng)前線(xiàn)程舵匾,便于開(kāi)發(fā)調(diào)試俊抵,這是最常用的一個(gè)方法,除此之外坐梯,下面的這幾個(gè)方法徽诲,使用頻率也是非常高,基于 NSObject
的 NSThreadPerformAdditions
分類(lèi)中的方法,繼承自 NSObject
的子類(lèi)都可以很方便的調(diào)用谎替。
// 當(dāng)前線(xiàn)程睡到指定時(shí)間
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
// 線(xiàn)程沉睡時(shí)間間隔 常用在設(shè)置啟動(dòng)頁(yè)間隔
[NSThread sleepForTimeInterval:1.0];
// 返回調(diào)用堆棧信息 可用于調(diào)試
// [NSThread callStackSymbols] return NSArray
// [NSThread callStackReturnAddresses] return NSArray
NSLog(@"callStackSymbols : %@", [NSThread callStackSymbols]);
NSLog(@"callStackReturnAddresses : %@", [NSThread callStackReturnAddresses]);
@interface NSObject (NSThreadPerformAdditions)
// 指定方法在主線(xiàn)程中執(zhí)行
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
// equivalent to the first method with kCFRunLoopCommonModes
// 指定方法在某個(gè)線(xiàn)程中執(zhí)行
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
// equivalent to the first method with kCFRunLoopCommonModes
// 指定方法在開(kāi)啟的子線(xiàn)程中執(zhí)行
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
@end
創(chuàng)建線(xiàn)程
-
實(shí)例方法創(chuàng)建線(xiàn)程
實(shí)例方法創(chuàng)建線(xiàn)程偷溺,可以根據(jù)需要設(shè)置參數(shù),調(diào)用- start()
才能開(kāi)啟線(xiàn)程钱贯,調(diào)用- cancel()
取消線(xiàn)程
// SEL
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(nsThreadMethod:) object:@"thread"];
NSThread *thread2 = [[NSThread alloc] init];
// block 方式
NSThread *thread3 = [[NSThread alloc] initWithBlock:^{
NSLog(@"block 創(chuàng)建 thread %s : %@", __func__, [NSThread currentThread]);
}];
// 設(shè)置名稱(chēng)
thread1.name = @"thread1";
// 設(shè)置線(xiàn)程優(yōu)先級(jí) 調(diào)度優(yōu)先級(jí)的取值范圍是0.0 ~ 1.0挫掏,默認(rèn)0.5,值越大秩命,優(yōu)先級(jí)越高砍濒。
thread3.threadPriority = 0.0;
// 啟動(dòng)線(xiàn)程
[thread1 start];
// 線(xiàn)程是否正在執(zhí)行
if ([thread3 isExecuting]) {
NSLog(@"thread1 is executing! ");
}
// 取消線(xiàn)程
[thread1 cancel];
// 線(xiàn)程是否撤銷(xiāo)
if ([thread1 isCancelled]) {
NSLog(@"thread1 canceled!");
}
// 線(xiàn)程是否執(zhí)行結(jié)束
if ([thread3 isFinished]) {
NSLog(@"thread3 is finished!");
}
-
類(lèi)方法創(chuàng)建線(xiàn)程
類(lèi)方法創(chuàng)建NSThread
不需要再調(diào)用start
方法,設(shè)置參數(shù)是通過(guò)類(lèi)方法設(shè)置
// block 方式
[NSThread detachNewThreadWithBlock:^{
NSLog(@"類(lèi)方法 block 創(chuàng)建 thread : %s : %@", __func__, [NSThread currentThread]);
}];
// SEL 方式
[NSThread detachNewThreadSelector:@selector(nsThreadMethod:) toTarget:self withObject:nil];
/*
[NSThread currentThread]; 獲取當(dāng)前線(xiàn)程
[NSThread isMultiThreaded]; 當(dāng)前代碼運(yùn)行線(xiàn)程是否為子線(xiàn)程
*/
// 當(dāng)前線(xiàn)程睡到指定時(shí)間
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
// 線(xiàn)程沉睡時(shí)間間隔 常用在設(shè)置啟動(dòng)頁(yè)間隔
[NSThread sleepForTimeInterval:1.0];
// 獲取線(xiàn)程優(yōu)先級(jí) / 設(shè)置優(yōu)先級(jí)
double priority = [NSThread threadPriority];
NSLog(@"當(dāng)前線(xiàn)程優(yōu)先級(jí) : %f", priority);
[NSThread setThreadPriority:0.9];
線(xiàn)程間通信
通常硫麻,例如我們有個(gè)網(wǎng)絡(luò)請(qǐng)求是在子線(xiàn)程中執(zhí)行爸邢,請(qǐng)求成功后我么要回到主線(xiàn)程中刷新UI,這是時(shí)候我們就需要了解子線(xiàn)程和主線(xiàn)程之間的通信拿愧,NSThread
為我們提供了解決方案杠河,調(diào)用 NSObject
和 NSObject (NSThreadPerformAdditions)
分類(lèi)中的方法,所有繼承自 NSObject
實(shí)例化對(duì)象都可調(diào)用以下方法
// 指定方法在主線(xiàn)程中執(zhí)行
[self performSelectorOnMainThread:@selector(performMethod:) // 要執(zhí)行的方法
withObject:nil // 執(zhí)行方法時(shí)浇辜,要傳入的參數(shù) 類(lèi)型為 id
waitUntilDone:YES]; // 當(dāng)前線(xiàn)程是否要被阻塞券敌,直到主線(xiàn)程將我們指定的代碼塊執(zhí)行完,當(dāng)前線(xiàn)程為主線(xiàn)程柳洋,設(shè)置為YES時(shí)待诅,會(huì)立即執(zhí)行,為NO時(shí)加入到RunLoop中在下一次運(yùn)行循環(huán)時(shí)執(zhí)行
[self performSelectorOnMainThread:@selector(performMethod:)
withObject:nil
waitUntilDone:YES
modes:@[@"kCFRunLoopDefaultMode"]];
// 指定方法在某個(gè)線(xiàn)程中執(zhí)行
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
// 在當(dāng)前線(xiàn)程上執(zhí)行操作熊镣,調(diào)用 NSObject 的 performSelector:相關(guān)方法
- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)object;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
// 指定方法在開(kāi)啟的子線(xiàn)程中執(zhí)行 (相當(dāng)于創(chuàng)建了一個(gè)子線(xiàn)程兴使,并且執(zhí)行方法)
[self performSelectorInBackground:@selector(performMethod:) withObject:nil];
舉個(gè)例子,我們來(lái)模擬網(wǎng)絡(luò)請(qǐng)求成功回到線(xiàn)程刷新 UI 的實(shí)現(xiàn)
// 開(kāi)辟子線(xiàn)程模擬網(wǎng)絡(luò)請(qǐng)求
[NSThread detachNewThreadWithBlock:^{
NSLog(@"類(lèi)方法 block 創(chuàng)建 thread : %s : %@", __func__, [NSThread currentThread]);
// 模擬網(wǎng)絡(luò)請(qǐng)求耗時(shí)操作
for (int i = 0; i < 2; i++) {
[NSThread sleepForTimeInterval:2];
NSLog(@"網(wǎng)絡(luò)請(qǐng)求中 %@",[NSThread currentThread]);
}
NSLog(@"網(wǎng)絡(luò)請(qǐng)求成功 準(zhǔn)備回到主線(xiàn)程刷新 UI %@",[NSThread currentThread]);
// 主線(xiàn)程刷新UI
[self performSelectorOnMainThread:@selector(mainThreadRefreshUI) withObject:nil waitUntilDone:YES];
}];
// 主線(xiàn)程刷新 UI 調(diào)用方法
- (void)mainThreadRefreshUI {
NSLog(@"回到了主線(xiàn)程并且刷新 UI %s : %@", __func__, [NSThread currentThread]);
}
跟我們預(yù)想的一樣套腹,網(wǎng)絡(luò)請(qǐng)求耗時(shí)操作是在子線(xiàn)程中執(zhí)行础淤,執(zhí)行結(jié)束后調(diào)用線(xiàn)程間通信方法回到了主線(xiàn)程刷新 UI。
以上是關(guān)于 NSThread
的介紹和簡(jiǎn)單使用的說(shuō)明鬼吵,相關(guān) demo 請(qǐng)參考
https://github.com/G-Jayson/Multi-thread