浅谈多线程——NSThread
生活随笔
收集整理的這篇文章主要介紹了
浅谈多线程——NSThread
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
上一篇文章中我們大致了解了GCD的模式和方法,在iOS開發中除了GCD之外,還有NSThread和NSOperation兩種多線程方式。
1.NSThread
- a - 使用NSThread開辟多線程進行子任務處理:類方法和初始化方法
使用類方法不需要創建對象就可以直接開辟多線程并發;而創建NSThread對象進行開辟則需要使用 - (void)start 方法進行線程啟動。
1 #import "ViewController.h" 2 3 typedef NS_ENUM(NSInteger, ENSThreadType) { 4 kNSThreadClassFunc, 5 kNSThreadInitFunc, 6 }; 7 8 @interface ViewController () 9 10 @end 11 12 @implementation ViewController 13 14 - (void)viewDidLoad { 15 [super viewDidLoad]; 16 17 [self threadWithType:kNSThreadInitFunc times:10]; 18 19 } 20 21 - (void)threadWithType:(ENSThreadType)type times:(int)time{ 22 for(int i = 0; i < time; i++){ 23 NSString *str = [NSString stringWithFormat:@"測試+%d", i]; 24 25 switch (type) { 26 case kNSThreadClassFunc:{ 27 // ①類方法 28 [NSThread detachNewThreadSelector:@selector(func:) toTarget:self withObject:str]; 29 } 30 break; 31 case kNSThreadInitFunc:{ 32 // ②初始化方法 33 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(func:) object:str]; 34 thread.name = str; 35 [thread start]; 36 } 37 break; 38 default: 39 break; 40 } 41 42 } 43 } 44 45 - (void)func:(NSString*)str{ 46 NSLog(@"%@ %@", str, [NSThread currentThread]); 47 } 48 49 @end
- b - NSThread實例方法,創建了NSThread對象后,可以調用它的實例方法:
1 #import "ViewController.h" 2 3 typedef NS_ENUM(NSInteger, ENSThreadObjFunc) { 4 // kThreadObjFuncThread, 5 kThreadObjFuncMain, 6 kThreadObjFuncBackground, 7 }; 8 9 @interface ViewController () 10 { 11 NSThread *aThread; 12 } 13 @end 14 15 @implementation ViewController 16 17 - (void)viewDidLoad { 18 [super viewDidLoad]; 19 20 aThread = [[NSThread alloc] initWithTarget:self selector:@selector(func:) object:@"測試參考線程"]; 21 [aThread start]; 22 23 [self threadObjFuncWithType:kThreadObjFuncMain thread:aThread times:10]; 24 25 } 26 27 - (void)func:(NSString*)str{ 28 NSLog(@"%@ %@", str, [NSThread currentThread]); 29 } 30 31 - (void)threadObjFuncWithType:(ENSThreadObjFunc)type thread:(NSThread*)thread times:(int)time{ 32 33 for(int i = 0; i < time; i ++){ 34 switch (type) { 35 case kThreadObjFuncMain:{ 36 // ①主線程隊列中執行,同步 37 NSString *str = [NSString stringWithFormat:@"主線程隊列+%d", i]; 38 [self performSelectorOnMainThread:@selector(func:) withObject:str waitUntilDone:YES]; 39 } 40 break; 41 case kThreadObjFuncBackground:{ 42 // ②后臺執行,并行異步 43 NSString *str = [NSString stringWithFormat:@"后臺執行+%d", i]; 44 [self performSelectorInBackground:@selector(func:) withObject:str]; 45 } 46 break; 47 // case kThreadObjFuncThread:{ 48 // ③在某一線程隊列執行,類似于串行異步 49 // NSString *str = [NSString stringWithFormat:@"方法+%d", i]; 50 // [self performSelector:@selector(func:) onThread:thread withObject:str waitUntilDone:YES]; 51 // } 52 // break; 53 default: 54 break; 55 } 56 } 57 } 58 59 @end?
轉載于:https://www.cnblogs.com/kriskee/p/5368155.html
總結
以上是生活随笔為你收集整理的浅谈多线程——NSThread的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS--viewController
- 下一篇: 【坑】执行Consumer的时候发生ja