1> 开线程的3种方式先创建,后启动
1 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; //object:run方法中传递的参数2 thread.name = @“线程名字”;3 thread.threadPriority = 1.0; //优先级4 [thread start];
直接启动(2种)
1 [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil]; 2 [self performSelectorInBackground:@selector(run) withObject:nil];
2> 其他方法
NSThread *current = [NSThread currentThread];//获得当前线程 + (NSThread *)mainThread; // 获得主线程
3>线程安全
1 前提:多个线程访问同一块资源的时候 2 解决方案:加互斥锁,加多把锁无效 3 相关代码:@synchronized(self){ //锁对象,全局唯一变量,一般写self加锁的代码 }
4 缺点:消耗大量CPU资源
5 原子和非原子属性,选中非原子属性(nonatomic)4> NSThread线程间通信
回到主线程刷新UI
//第一种方式 waitUntilDone:要不要等待调用方法执行完毕之后继续往下执行[self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];//第二种方式 利用self.imageView(里面有image属性),直接调用image属性的set方法就可以刷新UI,显示图片,而上面要实现showImage:方法[self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];//第三种方式 [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
5>常用的控制线程状态的方法
线程的各种状态:新建-就绪-运行-阻塞-死亡
[NSThread exit];//退出当前线程[NSThread sleepForTimeInterval:2.0];//阻塞线程[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];//阻塞线程
注意:线程死了不能复生