1、创建线程
第一种创建方式: alloc init特点:(1) 需要手动开启线程;(2) 可以拿到线程对象,进行详细设置; NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(showmsg) object:nil]; [thread start];iOS10方法 NSThread *thread = [NSThread alloc] initWithBlock:<#^(void)block#> [thread start]; 第二种创建方式:detachNewThreadSelector特点:自动启动线程,无法对线程进行更详细的设置[NSThread detachNewThreadSelector:@selector(showmsg) toTarget:self withObject:nil];第三种创建方式:performSelector方法[self performSelector:@selector(showmsg) withObject:nil];[self performSelectorOnMainThread:@selector(showmsg) withObject:nil waitUntilDone:YES];
2、设置线程属性
//设置线程的名称thread.name = @"111"//设置线程的优先级,注意线程优先级的取值范围为0.0~1.0之间,1.0表示线程的优先级最高,如果不设置该值,那么理想状态下默认为0.5thread.threadPriority = 1.0;
3、线程的状态
//线程的各种状态:新建-就绪-运行-阻塞-死亡//常用的控制线程状态的方法[NSThread exit];//退出当前线程[NSThread sleepForTimeInterval:2.0];//阻塞线程[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];//阻塞线程[NSThread isMainThread]//判断是否是主线程[_thread start];//开启线程_thread.isCancelled;//线程的状态是否是取消状态,[_thread cancel];//设置线程的状态为取消状态,cancel只能设置线程的状态,不会停止线程,退出线程需要调用,[NSThread exit]//注意:线程死了不能复生
4、线程间通讯
- (void)viewDidLoad { [super viewDidLoad]; //开启线程下载图片 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downLoadImage) object:nil]; [thread start]; }-(void)downLoadImage{ NSURL *url = [NSURL URLWithString:@"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png"]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *image = [UIImage imageWithData:data]; //回到主线程刷新界面 [_imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];}