首先,在了解多线程以前要了解什么是进程,什么是线程
进程是指在系统中正在运行的一个应用程序。每一个进程之间是独立的,每一个进程均运行在其专用且受保护的内存空间内。
一个进程要想执行任务,必须得有至少一个线程,线程是进程的基本执行单元,一个进程(程序)的全部任务都在线程中执行。
一个线程中任务的执行是串行的,若是要在1个线程中执行多个任务,那么只能一个一个地按顺序执行这些任务。也就是说,在同一时间内,1个线程只能执行1个任务。html
什么是多线程?
即在一个进程(程序)中能够开启多条线程,每条线程能够并行(同时)执行不一样的任务。ios
并行即同时执行。好比同时开启3条线程分别下载3个文件(分别是文件A、文件B、文件C)。程序员
在同一时间里,CPU只能处理一条线程,只有一条线程在工做(执行)。多线程并发(同时)执行,实际上是CPU快速地在多条线程之间快速切换,若是CPU调度线程的时间足够快,就形成了多线程并发执行的假象。设计模式
多线程优缺点
优势:安全
- 能适当提升程序的执行效率。
- 能适当提升资源利用率(CPU、内存利用率)
缺点:网络
- 开启线程须要占用必定的内存空间(默认状况下,主线程占用1M,子线程占用512KB),若是开启大量的线程,会占用大量的内存空间,下降程序的性能。
- 线程越多,CPU在调度线程上的开销就越大。
- 程序设计更加复杂:好比线程之间的通讯、多线程的数据共享
开启多线程的方式
当一个iOS程序运行后,默认会开启1条线程,称为“主线程”或“UI线程”;它的做用就是刷新显示UI,处理UI事件。多线程
- 不要将耗时操做放到主线程中去处理,会卡住线程。
- 和UI相关的刷新操做必须放到主线程中进行处理。
pthread
特色:并发
- 一套通用的多线程API
- 适用于UnixLinuxWindows等系统
- 跨平台可移植
使用难度:*****
使用语言:c语言
使用频率:几乎不用
线程生命周期:由程序员进行管理app
使用说明:pthread的基本使用(须要包含头文件)异步
具体实现代码:
1 2 3 4 5 6 7 8 9
|
pthread_t thread;
pthread_create(&thread, NULL, run, NULL);
|
NSThread
特色:
- 使用更加面向对象
- 简单易用,可直接操做线程对象
使用难度:***
使用语言:OC语言
使用频率:偶尔使用
线程生命周期:由程序员进行管理
建立线程
第一种建立线程的方式:alloc init
1 2 3 4 5 6 7 8 9
|
NSThread *newThread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[newThread start];
|
第二种建立线程的方式:分离出一条子线程
1 2 3 4 5 6 7
|
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
|
第三种建立线程的方式:后台线程
1 2 3 4 5 6
|
[self performSelectorInBackground:@selector(run) withObject:nil];
|
设置线程的属性
1 2 3 4 5
|
thread.name = @"线程A";
thread.threadPriority = 1.0;
|
线程的状态
线程的各类状态:新建-就绪-运行-阻塞-死亡
1 2 3 4 5
|
[NSThread exit]; [NSThread sleepForTimeInterval:2.0]; [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
|
线程安全
前提:多个线程访问同一块资源会发生数据安全问题
解决方案:加互斥锁
相关代码:@synchronized(self){}
专业术语-线程同步
原子和非原子属性(是否对setter方法加锁)
线程间通讯
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
-(void)touchesBegan:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event { [NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil]; } -(void)downloadImage { NSURL *url = [NSURL URLWithString:@"http://http://p2.wmpic.me/article/2016/03/17/1458205813_mEsdeUon.jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *image = [UIImage imageWithData:data];
[self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES]; }
|
如何计算代码段的执行时间
1 2 3 4 5 6 7 8 9 10 11
|
NSDate *start = [NSDate date];
NSData *data = [NSData dataWithContentsOfURL:url]; NSDate *end = [NSDate date]; NSLog(@"第二步操做花费的时间为%f",[end timeIntervalSinceDate:start]);
CFTimeInterval start = CFAbsoluteTimeGetCurrent(); NSData *data = [NSData dataWithContentsOfURL:url]; CFTimeInterval end = CFAbsoluteTimeGetCurrent(); NSLog(@"第二步操做花费的时间为%f",end - start);
|
GCD
特色:
- 旨在替代NSThread等线程技术
- 充分利用设备的多核(自动)
使用难度:**
使用语言:C语言
使用频率:常用
线程生命周期:自动管理
GCD基本使用
异步函数+并发队列:开启多条线程,并发执行任务
异步函数+串行队列:开启一条线程,串行执行任务
同步函数+并发队列:不开线程,串行执行任务
同步函数+串行队列:不开线程,串行执行任务
异步函数+主队列:不开线程,在主线程中串行执行任务
同步函数+主队列:不开线程,串行执行任务(注意死锁发生)
注意同步函数和异步函数在执行顺序上面的差别
GCD线程间通讯
建立串行队列
1 2 3 4 5
|
dispatch_queue_t queue2 = dispatch_queue_create(const char *label, DISPATCH_QUEUE_SERIAL);
|
建立并发队列
1 2 3 4 5
|
dispatch_queue_t queue2 = dispatch_queue_create(const char *label, DISPATCH_QUEUE_CONCURRENT);
|
建立全局队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{ NSURL *url = [NSURL URLWithString:@"http://p2.wmpic.me/article/2016/03/17/1458205813_mEsdeUon.jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *image = [UIImage imageWithData:data];
NSLog(@"下载操做所在的线程--%@",[NSThread currentThread]);
dispatch_async(dispatch_get_main_queue(), ^{ self.imageView.image = image; NSLog(@"刷新UI---%@",[NSThread currentThread]); }); });
|
GCD其它经常使用函数
栅栏函数(控制任务的执行顺序)
1 2 3
|
dispatch_barrier_async(queue, ^{ NSLog(@"--dispatch_barrier_async-"); });
|
延迟执行(延迟·控制在哪一个线程执行)
1 2 3
|
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSLog(@"---%@",[NSThread currentThread]); });
|
一次性代码(注意不能放到懒加载)
1 2 3 4 5 6 7 8 9
|
-(void)once { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSLog(@"-----"); }); }
|
快速迭代(开多个线程并发完成迭代操做)
1 2 3
|
dispatch_apply(subpaths.count, queue, ^(size_t index) {
});
|
队列组(同栅栏函数)
1 2 3 4 5 6
|
dispatch_group_t group = dispatch_group_create(); dispatch_group_notify(dispatch_group_t group, dispatch_queue_t queue, dispatch_block_t block);
|
注意事项:
在iOS6.0以前,在GCD中凡是使用了带Crearte和retain的函数在最后都须要作一次release操做。而主队列和全局并发队列不须要咱们手动release。在iOS6.0以后GCD已经被归入到了ARC的内存管理范畴中,即使是使用retain或者create函数建立的对象也再也不须要开发人员手动释放,咱们像对待普通OC对象同样对待GCD就OK。
在使用栅栏函数的时候,苹果官方明确规定栅栏函数只有在和使用create函数本身的建立的并发队列一块儿使用的时候才有效
NSOperation
特色:
- 基于GCD(底层是GCD)
- 比GCD多了一些更简单实用的功能
- 使用更加面向对象
使用难度:**
使用语言:OC语言
使用频率:常用
线程生命周期:自动管理
NSOperation是对GCD的包装,其自己是只是抽象类,只有它的子类(三个子类分别是:NSBlockOperation、NSInvocationOperation以及自定义继承自NSOperation的类)才能建立对象
NSInvocationOperation
1 2 3 4 5 6 7 8 9
|
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(run) object:nil];
[operation start];
|
NSBlockOperation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"---download1--%@",[NSThread currentThread]); }];
[operation addExecutionBlock:^{ NSLog(@"---download2--%@",[NSThread currentThread]); }]; [operation addExecutionBlock:^{ NSLog(@"---download3--%@",[NSThread currentThread]); }];
[operation start];
|
自定义NSOperation
1 2 3 4 5 6 7 8 9 10 11
|
-(void)main { NSLog(@"--main--%@",[NSThread currentThread]); }
TYOperation *op = [[TYOperation alloc]init];
[op start];
|
NSOperationQueue
NSOperation中的两种队列
- 主队列 经过mainQueue得到,凡是放到主队列中的任务都将在主线程执行
- 非主队列 直接alloc init出来的队列。非主队列同时具有了并发和串行的功能,经过设置最大并发数属性来控制任务是并发执行仍是串行执行
NSInvocationOperation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
- (void)invocation {
NSOperationQueue *queue = [[NSOperationQueue alloc]init]; NSInvocationOperation *op1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download1) object:nil]; NSInvocationOperation *op2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download2) object:nil]; NSInvocationOperation * 大专栏 iOS之多线程op3 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download3) object:nil]; [queue addOperation:op1]; [queue addOperation:op2]; [queue addOperation:op3]; }
|
NSBlockOperation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
- (void)freeBlock { NSOperationQueue *queue = [[NSOperationQueue alloc]init]; NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"1----%@",[NSThread currentThread]); }]; NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"2----%@",[NSThread currentThread]); }]; [op2 addExecutionBlock:^{ NSLog(@"3----%@",[NSThread currentThread]); }]; [op2 addExecutionBlock:^{ NSLog(@"4----%@",[NSThread currentThread]); }]; [queue addOperation:op1]; [queue addOperation:op2] [queue addOperationWithBlock:^{ NSLog(@"5----%@",[NSThread currentThread]); }]; }
|
自定义NSOperation
1 2 3 4 5 6 7 8 9 10 11 12 13
|
-(void)freeOperation {
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
TYOperation *op1 = [[TYOperation alloc]init]; TYOperation *op2 = [[TYOperation alloc]init];
[queue addOperation:op1]; [queue addOperation:op2]; }
|
NSOperation其它用法
设置最大并发数[最大并发数关系着队列是串行仍是并行]
建立队列
1
|
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
|
设置最大并发数
- 该属性须要在任务添加到队列中以前进行设置
- 该属性控制队列是串行执行仍是并发执行
- 若是最大并发数等于1,那么该队列是串行的,若是大于1那么是并行的
4.系统的最大并发数有个默认的值,为-1,若是该属性设置为0,那么不会执行任何任务
1
|
queue.maxConcurrentOperationCount = 2;
|
暂停和恢复以及取消
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
if (self.queue.isSuspended) { self.queue.suspended = NO; }else{ self.queue.suspended = YES; }
[self.queue cancelAllOperations]; ---------自定义NSOperation取消操做-------------------------- -(void)main { for (int i = 0; i<1000; i++) { NSLog(@"任务1-%d--%@",i,[NSThread currentThread]); } NSLog(@"+++++++++++++++++++++++++++++++++");
if (self.isCancelled) { return; }
for (int i = 0; i<1000; i++) { NSLog(@"任务1-%d--%@",i,[NSThread currentThread]); }
NSLog(@"+++++++++++++++++++++++++++++++++"); }
|
NSOperation实现线程间通讯
开子线程下载图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperationWithBlock:^{ NSURL *url = [NSURL URLWithString:@"http://p2.wmpic.me/article/2016/03/17/1458205813_mEsdeUon.jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *image = [UIImage imageWithData:data]; NSLog(@"下载图片操做--%@",[NSThread currentThread]); [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.imageView.image = image; NSLog(@"刷新UI操做---%@",[NSThread currentThread]); }]; }];
|
下载多张图片合成综合案例(设置操做依赖)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
- (void)download { NSOperationQueue *queue = [[NSOperationQueue alloc]init]; NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{ NSURL *url = [NSURL URLWithString:@"http://p2.wmpic.me/article/2016/03/14/1457926891_nZGraHTj.jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; self.image1 = [UIImage imageWithData:data]; }]; NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{ NSURL *url = [NSURL URLWithString:@"http://p3.wmpic.me/article/2016/01/08/1452222281_PmFnXZHU.jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; self.image2 = [UIImage imageWithData:data]; }];
NSBlockOperation *combine = [NSBlockOperation blockOperationWithBlock:^{
UIGraphicsBeginImageContext(CGSizeMake(200, 200));
[self.image1 drawInRect:CGRectMake(0, 0, 200, 100)];
[self.image2 drawInRect:CGRectMake(0, 100, 200, 100)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[[NSOperationQueue mainQueue]addOperationWithBlock:^{ self.imageView.image = image; NSLog(@"刷新UI---%@",[NSThread currentThread]); }];
}];
[combine addDependency:op1]; [combine addDependency:op2];
[queue addOperation:op1]; [queue addOperation:op2]; [queue addOperation:combine]; }
|
单例设计模式
iOS开发多种设计模式之一—-单例模式
什么是单例
在程序运行过程,一个类有且只有一个实例对象
使用场合
在整个应用程序中,共享一份资源(这份资源只须要建立初始化1次)
在不一样的内存管理机制下实现单例:
ARC实现单例
步骤:
- 在类的内部提供一个static修饰的全局变量
- 提供一个类方法,方便外界访问
- 重写+allocWithZone方法,保证永远都只为单例对象分配一次内存空间
- 严谨起见,重写-copyWithZone方法和-MutableCopyWithZone方法
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
static TYSingleTools *_instance;
+(instancetype)shareTools { return [[self alloc]init]; }
+(instancetype)allocWithZone:(struct _NSZone *)zone {
@synchronized(self) { if (_instance == nil) { _instance = [super allocWithZone:zone]; } } return _instance; }
-(nonnull id)copyWithZone:(nullable NSZone *)zone {
return _instance; } -(nonnull id)mutableCopyWithZone:(nullable NSZone *)zone { return _instance; }
|
MRC实现单例
步骤:
- 在类的内部提供一个static修饰的全局变量
- 提供一个类方法,方便外界访问
- 重写+allocWithZone方法,保证永远都只为单例对象分配一次内存空间
- 严谨起见,重写-copyWithZone方法和-MutableCopyWithZone方法
- 重写release和retain方法
- 建议在retainCount方法中返回一个最大值(有经验的程序员经过打印retainCount这个值能够猜到这是一个单例)
配置MRC环境知识:
- 注意ARC不是垃圾回收机制,是编译器特性
- 配置MRC环境:build setting ->搜索automatic ref->修改成NO
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
static TYSingleTools *_instance;
+(instancetype)shareTools { return [[self alloc]init]; }
+(instancetype)allocWithZone:(struct _NSZone *)zone {
@synchronized(self) { if (_instance == nil) { _instance = [super allocWithZone:zone]; } } return _instance; }
-(nonnull id)copyWithZone:(nullable NSZone *)zone {
return _instance; } -(nonnull id)mutableCopyWithZone:(nullable NSZone *)zone { return _instance; }
-(oneway void)release { } -(instancetype)retain { return _instance; }
-(NSUInteger)retainCount { return MAXFLOAT; }
|
- 忽略ARC和MRC的单例通用版本
可使用条件编译来判断当前项目环境是ARC仍是MRC,从而实现一份代码在不一样的内存管理机制下均可以实现单例。
1 2 3 4 5 6
|
条件编译: #if __has_feature(objc_arc) //若是是ARC,那么就执行这里的代码1 #else //若是不是ARC,那么就执行代理的代码2 #endif
|
注意:单例是不能够用继承的。
参考资料