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线程继续进行操作