多线程知识点总结 -NSThread4

时间:2021-09-21 14:29:29

NSThread

三种创建方式

NSThread的对象方法
- (void)threadDemo1 {
NSLog(@"before %@", [NSThread currentThread]); NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(longOperation:) object:@"THREAD"]; [thread start]; NSLog(@"after %@", [NSThread currentThread]);
}
小结:在start方法执行完毕后,会在另一个线程执longOperation:方法  NSThread的类方法
- (void)threadDemo2 {
NSLog(@"before %@", [NSThread currentThread]); [NSThread detachNewThreadSelector:@selector(longOperation:) toTarget:self withObject:@"DETACH"]; NSLog(@"after %@", [NSThread currentThread]);
}

小结:detachNewThreadSelector:类方法不需要启动;会自动创建线程并执行@selector方法
NSThread的类方法
- (void)threadDemo3 {
NSLog(@"before %@", [NSThread currentThread]); [self performSelectorInBackground:@selector(longOperation:) withObject:@"PERFORM"]; NSLog(@"after %@", [NSThread currentThread]);
}
小结:这是NSObject的分类方法,会在后台自动执行@selector方法;