1.获取主线程方法:
NSThread *mainT = [NSThread mainThread];
NSLog(@"主线程:%@",mainT);
显示结果:{name = (null),num = 1}
请记住:num = 1,才是主线程。num 相当于线程的ID。
2.获取当前线程方法:
NSThread *currentT = {NSThread currentThread];
3.创建线程:
使用方法:- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
(1)创建方法:NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(runThread:) object:@"run"];
[thread start]; //开启线程
-(void)runThread:(NSString *)string{
NSThread *currentT = [NSThread currentThread]; //当前线程
NSLog(@"执行runThread:方法,参数%@,当前线程:%@",string,currentT); //打印当前线程参数
}
结果:执行runThread:方法,参数run,当前线程{name = (null),num = 3}
num值为3,不是主线程,主线程num值为1.
(2)+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;静态方法获取线程
[NSThread detachNewThreadSelector:@selector(runThread:) toTarget:self withObject:@"run"]; 调用方法(启动一个新的线程,调用self的runThread:方法,以run为参数)
(3)[self performSelectorInBackground:@selector(runThread:) withObject:@"run"]; 隐式创建线程
4.暂停当前线程:
(1)[NSThread sleepForTimeInterval:5]; //快捷方法暂停5秒
(2)NSDate *date = [NSDate dateWithTimeInterval:5 sinceDate:[NSDate date]];
[NSThread sleepUntilDate:date]; //另一种方法暂停5秒
(1)在主线程上的执行操作:
[self performSelectorOnMainThread:@selector(runThread:) withObject:nil waitUntilDone:YES]; //在主线程上调用 runThread:方法
(2)在当前线程执行操作:[self performSelector:@selector(runThread:) withObject:nil]; //在当前线程调用runThread:方法
(3)在指定线程执行操作:
[self performSelector:@selector(runThread:) onThread:myThread withObject:nil waitUntilDone:YES]; //在myThread线程上调用 runThread:方法 YES :runThread:方法执行完毕才会继续往下执行其他代码
6.Thread线程更直观控制线程对象,需要管理线程的生命周期,线程同步。线程同步对数据的加锁会占用系统一定的内存。