iOS-多線程之NSThread

NSThread簡介

NSThread是基於線程使用,輕量級的多線程編程方法(相對GCD和NSOperation),一個NSThread對象代表一個線程,需要手動管理線程的生命週期,處理線程同步等問題。

屬性和方法

屬性和方法 解釋
isExecuting 線程是否在執行
isCancelled 線程是否被取消
isFinished 線程是否完成
isMainThread 是否是主線程
threadPriority 線程的優先級,取值範圍0.0到1.0,默認優先級0.5,1.0表示最高優先級,優先級高,CPU調度的頻率高
+(NSThread *)currentThread 獲取當前線程
+(void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument 創建啓動線程
+(BOOL)isMultiThreaded 判斷是否是多線程
+(void)sleepUntilDate:(NSDate *)date 線程休眠到NSDate
+(void)sleepForTimeInterval:(NSTimeInterval)time 線程休眠NSTimeInterval
-(void)start 啓動線程
+(void)exit 結束/退出當前線程
+(double)threadPriority 獲取當前線程優先級
+(BOOL)setThreadPriority:(double)priority 設置線程優先級 默認爲0.5 取值範圍爲0.0 - 1.0,1.0優先級最高
+(BOOL)isMainThread NS_AVAILABLE(10_5, 2_0) 判斷當前線程是否是主線程
+(NSThread *)mainThread NS_AVAILABLE(10_5, 2_0) 獲取主線程
-(double)threadPriority NS_AVAILABLE(10_6, 4_0) 獲取指定線程的優先級
-(void)setThreadPriority:(double)p NS_AVAILABLE(10_6, 4_0) 設置指定線程的優先級
-(void)setName:(NSString *)n NS_AVAILABLE(10_5, 2_0) 設置線程的名字
-(NSString *)name NS_AVAILABLE(10_5, 2_0) 獲取線程的名字
-(BOOL)isMainThread NS_AVAILABLE(10_5, 2_0) 判斷指定的線程是否是 主線程
-(id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument NS_AVAILABLE(10_5, 2_0) 創建線程
-(BOOL)isExecuting NS_AVAILABLE(10_5, 2_0) 指定線程是否在執行
-(BOOL)isFinished NS_AVAILABLE(10_5, 2_0) 線程是否完成
-(BOOL)isCancelled NS_AVAILABLE(10_5, 2_0) 線程是否被取消 (是否給當前線程發過取消信號)
-(void)cancel NS_AVAILABLE(10_5, 2_0) 發送線程取消信號的 最終線程是否結束 由 線程本身決定
-(void)start NS_AVAILABLE(10_5, 2_0) 啓動線程
-(void)main NS_AVAILABLE(10_5, 2_0) 線程主函數 在線程中執行的函數 都要在-main函數中調用,自定義線程中重寫-main方法

使用方法

方式1
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(doSth) object:nil];
    thread.name = @"thread1";
    [thread start];
- (void)doSth{
    NSLog(@"%@",[NSThread currentThread]);
}

打印結果
2019-11-15 13:24:33.655155+0800 iosTest[33058:1857339] <NSThread: 0x600003fbf9c0>{number = 3, name = thread1}

方式2

該方法會自動創建一個子線程,並在子線程中執行。

[NSThread detachNewThreadSelector:@selector(doSth) toTarget:self withObject:nil];
- (void)doSth{
    NSLog(@"%@",[NSThread currentThread]);
}

打印結果
2019-11-15 13:26:54.993327+0800 iosTest[33108:1859499] <NSThread: 0x6000018152c0>{number = 3, name = (null)}

方式3

該方法會開啓一條後臺線程,並在後臺線程中執行。

[self performSelectorInBackground:@selector(doSth) withObject:nil];
- (void)doSth{
    NSLog(@"%@",[NSThread currentThread]);
}
方式4

在主線程上執行任務,即返回主線程。

[self performSelectorOnMainThread:@selector(doSth) withObject:nil waitUntilDone:NO];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章