多线程开发之NSThrea

创建并启动

先创建线程,再启动

// 创建
  NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:nil];
  // 启动
  [thread start];
 
创建并启动
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:nil];

隐式创建并启动

[self performSelectorInBackground:@selector(run:) withObject:@"mj"]; 

其他方法

在指定线程上执行操作

[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES]; 

上面代码的意思是在thread这条线程上调用self的run方法

 最后的YES代表:上面的代码会阻塞,等run方法在thread线程执行完毕后,上面的代码才会通过

在主线程上执行操作

[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];  

在当前线程执行操作

[self performSelector:@selector(run) withObject:nil]; 

//取消线程
- (void)cancel;
//启动线程
- (void)start;
//判断某个线程的状态的属性
@property (readonly, getter=isExecuting) BOOL executing;
@property (readonly, getter=isFinished) BOOL finished;
@property (readonly, getter=isCancelled) BOOL cancelled;
//设置和获取线程名字
-(void)setName:(NSString *)n;
-(NSString *)name;
//获取当前线程信息
+ (NSThread *)currentThread;
//获取主线程信息
+ (NSThread *)mainThread;
//使当前线程暂停一段时间,或者暂停到某个时刻
+ (void)sleepForTimeInterval:(NSTimeInterval)time;
+ (void)sleepUntilDate:(NSDate *)date;
 
优缺点:
优点:NSThread比其他多线程方案较轻量,更直观地控制线程对象
缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销
 
 
posted @ 2017-08-12 14:23  LiLM  阅读(308)  评论(0编辑  收藏  举报