NSTread

1.NSTread

首先介绍一下NSTread的特点:每个NSThread对象对应一个线程,量级较轻,更直观地控制线程对象,但需要管理线程的生命周期、同步、加锁问题,这会导致一定的性能开销。

下面介绍一下NSTread的方法和使用:

1》初始化线程initWithTarget为成员方法,需用start执行选择器方法:

//   object:(此处为timeSel方法的参数,可为nil)
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(timeSel) object:nil];  
// 设置线程的优先级(0.0 - 1.0,1.0最高级)  
thread.threadPriority = 1;  
// 开启线程  
[thread start];

2》detachNewThreadSelector为NSThread的类方法,直接启动线程并调用方法:

 // 新建一个线程,调用@selector方法 
[NSThread detachNewThreadSelector:@selector(timeSel) toTarget:self withObject:nil];

3》隐式创建线程的方法,performSelectorInBackground是将timeSel的任务放在后台线程中执行

[self performSelectorInBackground:@selector(timeSel) withObject:nil];

4》线程间通讯

(1)指定线程执行timeSel

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

(2)主线程执行timeSel

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

(3)当前线程执行timeSel

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

5》获取当前线程

NSThread *currentThread = [NSThread currentThread];

6》获取主线程

NSThread *mainThread = [NSThread mainThread];  

7》暂停当前线程

// 暂停7s  
[NSThread sleepForTimeInterval:7];  

// 或者  
NSDate *dateTime = [NSDate dateWithTimeInterval:7 sinceDate:[NSDate date]];  
[NSThread sleepUntilDate:dateTime]; //睡眠,直到时间dateTime线程继续进行操作
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值