IOS多线程编程NSThread的使用方法

2020-01-21 01:28:44于丽

IOS多线程编程NSThread的使用方法

NSThread是多线程的一种,有两种方法创建子线程

(1)优点:NSThread 比GCD、NSOperation都轻量级

(2)缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销

第一种是隐藏创建,有以下几种方式:

(1)多用于串行:- (id)performSelector:(SEL)aSelector withObject:(id)object;
(2)后台执行,多用于并行:- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg;
(3)延迟执行:- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;
(4)回到主线程执行:- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
注意:
(1)通过方法" + (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(nullable id)anArgument; ",或"+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget"停止执行; 

示例:

//创建子线程-隐式方法


// 子线程-串行 
[self performSelector:@selector(showCount:) withObject:@(11)]; 
[self performSelector:@selector(showCount:) withObject:@(12)]; 
[self performSelector:@selector(showCount:) withObject:@(23)]; 


// 子线程-并行(后台)  
[self performSelectorInBackground:@selector(showCount:) withObject:@(41)]; 
[self performSelectorInBackground:@selector(showCount:) withObject:@(42)]; 

// 回到主线程 
[self performSelectorOnMainThread:@selector(showCount:) withObject:@(51) waitUntilDone:YES]; 


// 子线程延迟执行 
[self performSelector:@selector(showCount:) withObject:@(61) afterDelay:5.0]; 

// 停止 
[NSObject cancelPreviousPerformRequestsWithTarget:self]; 

 第二种是显示创建,方式如下:


 - (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument; 

注意:

 (1)通过方法" - (void)start; "开始执行;
 (2)通过方法" - (void)cancel; "停止执行;  

 示例:

 //创建子线程-显示方法


self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(showCount:) object:@(61)]; 
self.thread.name = @"计数"; 
[self.thread start]; 
[self.thread cancel]; 

代码示例


- (void)showCount:(NSNumber *)number 
{ 
 NSInteger count = arc4random() % 1000; 
 count = 1000; 
 for (int i = 0; i < count; i++) 
 { 
  NSLog(@"第 %@ 个 i = %@", number, @(i)); 
   
  // 休眠n秒再执行 
  [NSThread sleepForTimeInterval:0.2]; 
   
  // 停止 
//  BOOL isStop = [self.thread isCancelled]; 
//  if (isStop) 
//  { 
//   NSLog(@"2 停止"); 
//   break; 
//  } 
  if (isCancelThread) 
  { 
   NSLog(@"2 停止"); 
   break; 
  } 
 } 
}