iOS浅谈多线程之NSThread
2018-10-09 本文已影响8人
元宝是只小肥猫
基本概念
进程:进程是指在系统中正在运行的一个应用程序。每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内。
线程:1个进程要想执行任务,必须得有线程(每1个进程至少要有1条线程),线程是进程的基本执行单元,一个进程(程序)的所有任务都在线程中执行。
串行:在一个线程中执行多个任务,并且只能一个一个顺序执行
并发:在一个线程中多个任务同时执行。
同步:只能在当前线程中执行任务,不具备开启新线程的能力
异步:可以在新的线程中执行任务,具备开启新线程的能力
多线程:一个进程中可以开启多个线程,每条线程可以并发(同时)执行不同任务
多线程的原理
同一时间,CPU只能处理1条线程,只有1条线程在工作(执行)
多线程并发(同时)执行,其实是CPU快速地在多条线程之间调度(切换)
如果CPU调度线程的时间足够快,就造成了多线程并发执行的假象
思考:如果线程非常非常多,会发生什么情况?
CPU会在N多线程之间调度,CPU会累死,消耗大量的CPU资源
每条线程被调度执行的频次会降低(线程的执行效率降低)
基础使用
@property (readonly) BOOL isMainThread;
@property (class, readonly) BOOL isMainThread
- (void)viewDidLoad {
[super viewDidLoad];
NSThread *mainThread = [NSThread mainThread];
NSThread *currentThread = [NSThread currentThread];
//判断是否是主线程
BOOL isMainThread = [NSThread currentThread].isMainThread;
isMainThread = [NSThread isMainThread];
}
开启新的线程
线程的生命周期:当线程中的任务执行完毕后被释放
//方式1
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(gotoLoad:) object:@"lxx"];
[thread start];
//方式2
[NSThread detachNewThreadSelector:@selector(gotoLoad:) toTarget:self withObject:@"dxx"];
//方式3
[self performSelectorInBackground:@selector(gotoLoad:) withObject:@"lmy"];
下载图片
- (void)showImg {
NSString *url = @"www.xxxxx";
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(downloadImgFromURL:) object:url];
thread.threadPriority = 0.8;//设置优先级:0-1
[thread start];
}
- (void)downloadImgFromURL:(NSString *)URL {
NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:URL]];
UIImage *img = [[UIImage alloc]initWithData:data];
if (img) {//拿到数据,回主线程刷新UI
//方式1:
//第三个参数:是否等待
[self performSelectorOnMainThread:@selector(updateUI:) withObject:img waitUntilDone:YES];
//方式2:
[self performSelector:@selector(updateUI:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
}
}
- (void)updateUI:(UIImage *)img {
}
//方式3:简单方式
//通过imageVIew来调用他的set方法来实现少写一步的操作
[imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
控制线程状态
线程的各种状态:新建-就绪-运行-阻塞-死亡
线程的状态:就绪状态(Runnable) 阻塞状态(Blocked)运行状态(Running)
[thread start];
- (void)gotoLoad:(NSString *)parm {
NSLog(@"----%@,%@",parm,[NSThread currentThread]);
[NSThread sleepForTimeInterval:2];//阻塞线程2秒
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
[NSThread exit];//强制退出当前线程
}
计算耗时操作的时间差
//方式1
CFTimeInterval start = CFAbsoluteTimeGetCurrent();
CFTimeInterval end = CFAbsoluteTimeGetCurrent();
NSLog(@"%f",end - start);
//方式2:
NSDate *startDate = [NSDate date];
NSDate *endDate = [NSDate date];
NSTimeInterval time = [endDate timeIntervalSinceDate:startDate];
互斥锁使用格式
@synchronized(锁对象) { // 需要锁定的代码 } 注意:锁定1份代码只用1把锁,用多把锁是无效的
互斥锁的优缺点
优点:能有效防止因多线程抢夺资源造成的数据安全问题
缺点:需要消耗大量的CPU资源
互斥锁的使用前提:多条线程抢夺同一块资源
线程同步
线程同步的意思是:多条线程在同一条线上执行(按顺序地执行任务)
互斥锁,就是使用了线程同步技术
OC在定义属性时有nonatomic和atomic两种选择
atomic:原子属性,为setter方法加锁(默认就是atomic)
nonatomic:非原子属性,不会为setter方法加锁