iOS多线程实现方案
GCD(Grand Central Dispatch)
一、基本用法
GCD会自动利用更多的CPU内核(比如双核、四核)。
GCD会自动管理线程的生命周期(创建线程、调度任务、销毁线程)。
只需要告诉GCD想要执行什么任务,不需要编写任何线程管理代码。
01 异步函数+并发队列:开启多条线程,并发执行任务 //start end...在多条线程
02 异步函数+串行队列:开启一条线程,串行执行任务//start end...为串行队列开启一个线程
03 同步函数+并发队列:不开线程,串行执行任务 //start...end在当前线程
04 同步函数+串行队列:不开线程,串行执行任务//start...end在当前线程
05 异步函数+主队列:不开线程,在主线程中串行执行任务//start end...主队列:在主线程执行
06 同步函数+主队列:不开线程,串行执行任务(注意死锁发生)
07 使用sync函数往当前串行队列中添加任务,会卡住当前的(线程.)串行队列
- 例子: 异步+串行队列
NSLog(@"----start-%@" , [NSThread currentThread]);
dispatch_queue_t queue1 = dispatch_queue_create("download1", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t queue2 = dispatch_queue_create("queue2", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue2, ^{
NSLog(@"---queue2222---%@",[NSThread currentThread]);
});
dispatch_async(queue1, ^{
NSLog(@"---download1---%@",[NSThread currentThread]);
});
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"---download2---%@",[NSThread currentThread]);
});
dispatch_async(queue1, ^{
NSLog(@"---download3---%@",[NSThread currentThread]);
});
dispatch_async(queue1, ^{
NSLog(@"---download4---%@",[NSThread currentThread]);
});
NSLog(@"----end-%@", [NSThread currentThread]);
//----start-{number = 1, name = main}
//----end-{number = 1, name = main}
//---download1---{number = 6, name = (null)}
//---queue2222---{number = 5, name = (null)}
//---download3---{number = 6, name = (null)}
//---download2---{number = 1, name = main}
//---download4---{number = 6, name = (null)}
- 例子2:死锁
//使用sync往主队列加任务并不一定死锁。
//在子线程的当前串行队列继续加任务也会死锁。
dispatch_async(dispatch_queue_create("q", DISPATCH_QUEUE_SERIAL), ^{
NSLog(@"-----%@",[NSThread currentThread]);
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"不会死锁===%@",[NSThread currentThread]);
});
dispatch_sync(dispatch_get_current_queue(), ^{
NSLog(@"会死锁-----%@",[NSThread currentThread]);
});
});
//-----{number = 6, name = (null)}
//不会死锁==={number = 1, name = main}
//卡死
二、其他方法
- dispatch_group_t队列组 dispatch_group_async dispatch_group_notify
只能保证执行当前线程任务完成后notify,不能保证二级任务
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t q = dispatch_get_global_queue(0, 0);
dispatch_group_async(group, q, ^{
for(NSInteger i = 0; i < 100; i++)
{
NSLog(@"++++%ld", (long)i);
}
dispatch_async(q, ^{
for(NSInteger i = 0; i < 200; i++)
{
NSLog(@"-----%ld", (long)i);
}
});
});
dispatch_group_notify(group, q, ^{
NSLog(@"======");
});
//++++99
//-----0
//======
//-----1
- dispatch_group_enter dispatch_group_leave 可以保证子任务
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
for(NSInteger i = 0; i < 100; i++)
{
NSLog(@"++++%ld", (long)i);
}
dispatch_group_leave(group);
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for(NSInteger i = 0; i < 200; i++)
{
NSLog(@"-----%ld", (long)i);
}
dispatch_group_leave(group);//写在async函数里才可
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"======");
});
- dispatch_barrier_async栅栏函数,用来控制并发队列的执行顺序
- dispatch_after延迟执行
//表名2秒钟之后调用run
// [self performSelector:@selector(run) withObject:nil afterDelay:2.0];
// [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
/*
第一个参数:延迟时间
第二个参数:要执行的代码
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
NSLog(@"---%@",[NSThread currentThread]);
});
- dispatch_once_t整个程序运行后只执行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
});
- dispatch_apply创建多条线程执行
//创建队列(并发队列)
dispatch_queue_t queue = dispatch_queue_create("com.downloadqueue", DISPATCH_QUEUE_CONCURRENT);
/*
第一个参数:迭代的次数
第二个参数:在哪个队列中执行
第三个参数:block要执行的任务
*/
dispatch_apply(10, queue, ^(size_t index) {
NSLog(@"%zd--%@",index,[NSThread currentThread]);
});
//文件在哪个地方(文件夹)
NSString *form = @"/Users/xiaomage/Desktop/form";
//要剪切到什么地方
NSString *to = @"/Users/xiaomage/Desktop/to";
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *subpaths = [manager subpathsAtPath:form];
//NSDirectoryEnumerator *enumer = [manager enumeratorAtPath:to];//可以打印嵌套文件夹下文件路径
//NSDirectoryEnumerator *enumer = [manager contentsOfDirectoryAtPath:to error:nil];
//for (NSDirectoryEnumerator *en in enumer) {
// NSLog(@"%@",en);
// }
// NSLog(@"%@",subpaths);
NSInteger count = [subpaths count];
for (NSInteger i = 0; i]
NSString *subpath = subpaths[i];
NSString *fullPath = [form stringByAppendingPathComponent:subpath];
//拼接目标文件全路径
NSString *fileName = [to stringByAppendingPathComponent:subpath];
//剪切操作
[manager moveItemAtPath:fullPath toPath:fileName error:nil];
NSLog(@"%@--%@",fullPath,fileName);
}
NSOperationQueue
一、NSOperation
- NSInvocationOperation
/*
第一个参数:目标对象
第二个参数:选择器,要调用的方法
第三个参数:方法要传递的参数
*/
// NSInvocationOperation *op = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download) object:nil];
//
// //启动操作
// [op start];
- NSBlockOperation
//1.封装操作//在主线程
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"1------%@",[NSThread currentThread]);
}];
//2.追加操作//在子线程中并发执行
[op1 addExecutionBlock:^{
NSLog(@"2------%@",[NSThread currentThread]);
}];
[op1 addExecutionBlock:^{
NSLog(@"3------%@",[NSThread currentThread]);
}];
- 写一个类继承NSOperation,重新main方法。[op start];时调用main方法。
二、 NSOperationQueue
1.将操作放入,系统自动异步执行
- NSInvocationOperation添加到操作队列
/*
主队列:凡是放到主队列里面的任务都在主线程执行[NSOperationQueue mainQueue]
非主队列:alloc int,同时具备了并发和串行的功能,默认是并发队列
*/
//1.创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
//2.封装操作
NSInvocationOperation *op1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download1) object:nil];
NSInvocationOperation *op2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download2) object:nil];
NSInvocationOperation *op3 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download3) object:nil];
//3.添加操作到队列,系统自动异步执行
[queue addOperation:op1]; //[op1 start]
[queue addOperation:op2];
[queue addOperation:op3];
-(void)download1
{
NSLog(@"download1---%@",[NSThread currentThread]);
}
- NSBlockOperation添加到操作队列
//1.创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
//2.封装操作
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"1----%@",[NSThread currentThread]);
}];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"2----%@",[NSThread currentThread]);
}];
[op2 addExecutionBlock:^{
NSLog(@"3----%@",[NSThread currentThread]);
}];
//3.添加操作到队列
[queue addOperation:op1]; //[op1 start]
[queue addOperation:op2];
//简便方法
[queue addOperationWithBlock:^{
NSLog(@"4----%@",[NSThread currentThread]);
}];
- 继承类类型
//1.创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
//2.封装操作
XMGOperation *op1 = [[XMGOperation alloc]init];
XMGOperation *op2 = [[XMGOperation alloc]init];
//3.添加操作到队列
[queue addOperation:op1]; //[op1 start]
[queue addOperation:op2];
2.其他
- maxConcurrentOperationCount
默认是最大并发数-1是并发队列,如果最大并发数>1,并发
如果最大并发数==1,串行队列(也可能有多个线程) - suspended YES暂停NO恢复
只能暂停队列中后面的操作,不能暂停正在执行的操作。 - cancelAllOperations 取消,不再执行 operation.isCancelled判断操作是否已取消
- 操作监听和依赖
//1.创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSOperationQueue *queue1 = [[NSOperationQueue alloc]init];
//2.封装操作
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"1----%@",[NSThread currentThread]);
}];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"2----%@",[NSThread currentThread]);
}];
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"3----%@",[NSThread currentThread]);
}];
NSBlockOperation *op4 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"4----%@",[NSThread currentThread]);
}];
NSBlockOperation *op5 = [NSBlockOperation blockOperationWithBlock:^{
for (NSInteger i=0; i<1000; i++) {
NSLog(@"5-%zd---%@",i,[NSThread currentThread]);
}
}];
op4.completionBlock = ^{
NSLog(@"op4已经完成了---%@",[NSThread currentThread]);
};
//添加操作依赖,注意不能循环依赖
//也可以依赖其他队列的操作
[op1 addDependency:op5];
[op1 addDependency:op4];
//添加操作到队列
[queue addOperation:op1];
[queue addOperation:op2];
[queue addOperation:op3];
[queue addOperation:op4];
[queue1 addOperation:op5];
- 线程间通信
//1.创建队列
NSOperationQueue *queue= [[NSOperationQueue alloc]init];
//2.下载图片
[queue addOperationWithBlock:^{
//2.1.确定要下载网络图片的url地址,一个url唯一对应着网络上的一个资源
NSURL *url = [NSURL URLWithString:@"http://p6.qhimg.com/t01d2954e2799c461ab.jpg"];
//2.2.根据url地址下载图片数据到本地(二进制数据)
NSData *data = [NSData dataWithContentsOfURL:url];
//2.3.把下载到本地的二进制数据转换成图片
UIImage *image = [UIImage imageWithData:data];
//3.回到主线程刷新UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.imageView.image = image;
NSLog(@"%@----",[NSThread currentThread]);
}];
}];
NSThread
/*
第一个参数:目标对象
第二个参数:选择器,调用哪个方法
第三个参数:前面方法需要传递的参数
*/
NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
//设置基本属性
thread1.name = @"线程1";
//线程优先级
[thread1 setThreadPriority:1.0];//默认0.5,cpu调度线程的概率
//开启线程
[thread1 start];
/*
第一个参数:选择器,调用哪个方法
第二个参数:目标对象
第三个参数:前面方法需要传递的参数
*/
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"参数"];
/*
第三种创建线程的方式
特点:默认开启线程
*/
[self performSelectorInBackground:@selector(run:) withObject:@"后台线程"];
pthread了解
//创建线程
pthread_t thread;
/*
第一个参数:线程对象
第二个参数:线程属性
第三个参数:void *(*)(void *) 指向函数的指针
第四个参数:函数的参数
*/
pthread_create(&thread, NULL, run, NULL);
pthread_t thread1;
pthread_create(&thread1, NULL, run, NULL);
//void *(*)(void *)
void *run(void *param)
{
// NSLog(@"---%@-",[NSThread currentThread]);
for (NSInteger i =0 ; i<10000; i++) {
NSLog(@"%zd--%@-",i,[NSThread currentThread]);
}
return NULL;
}