NSThread

每个iOS应用程序都是一个进程,而一个进程中都有一个一直存在的主线程,用来更新UI界面、处理用户的触摸事件,因此不能将其他太耗时的操作放在主线程中执行,不然会造成主线程堵塞(出现卡机现象),带来极坏的用户体验。解决方法就是把耗时操作放到另一个线程中去执行,多线程编程是防止主线程堵塞,增加运行效率的最佳方法
NSThread
1、动态方法
(id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
代码:
// 初始化线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
// 设置线程名字
thread.name = @“thread A”;
// 设置线程的优先级(0.0 - 1.0,1.0最高级)
thread.threadPriority = 1;
// 开启线程
[thread start];

2、静态方法
(void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
代码:
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
// 调用完毕后,会马上创建并开启新线程
3、隐式创建线程的方法
(void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg
代码:
[self performSelectorInBackground:@selector(run) withObject:nil];

二、NSThread常用方法
获取当前线程
NSThread *current = [NSThread currentThread];

获取主线程
NSThread *main = [NSThread mainThread];

暂停当前线程
// 暂停多少秒
[NSThread sleepForTimeInterval:2];
// 暂停到什么时间段
[NSThread sleepUntilDate:date];

强制停止线程
[NSThread exit];
注意:一旦线程停止(死亡)了,就不能再次开启任务

三、线程间的通信
1、在指定线程上执行操作
[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];

2、在主线程上执行操作
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];

3、在当前线程执行操作
[self performSelector:@selector(run) withObject:nil];

四、优缺点
1、优点:NSThread比其他两种多线程方案较轻量级,更直观地控制线程对象
2、缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值