常用的控制线程状态的方法 ```objc [NSThread exit];//退出当前线程 [NSThread sleepForTimeInterval:7.0];//阻塞线程 [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:7.0]];//阻塞线程
``##注意:线程死亡后不能复生`
1.包含头文件(必须)
#import <pthread.h>2.创建线程
// 创建线程 /** * * 参数一:线程对象(传地址) * 参数二:线程的属性(名称\优先级) * 参数三:只想函数的指针 * 参数四:函数需要接受的字符串参数,可以不传递(注:由于我们创建的是OC的字符串,所以在传值的时候需要将其转换成C的字符串) */ pthread_t thread; NSString *num = @"123"; pthread_create(&thread, NULL, task, (__bridge void *)(num));3.定义参数所需要的函数指针
void *task(void *num) { NSLog(@"当前线程 -- %@,传入的参数:-- %@", [NSThread currentThread], num); return NULL; }如果需要退出线程的话只需调用下面代码
pthread_exit(NULL);运行结果:
1.创建自定义类继承自NSThread 2.重写NSThread类中的main方法
- (void)main { NSLog(@"当前线程--%@", [NSThread currentThread]); }3.创建线程对象
/** * NSThread创建一条后台线程 */ - (void)nsthreadTest4 { // 创建线程 SJThread *thread = [[SJThread alloc] init]; // 开启执行 [thread start]; }有时候我们会从服务器上下载图片然后再展示出来,下载的操作我们会放到子线程,而UI刷新的操作只能在主线程中执行。这样就涉及到线程间的通信。接下来我们分三种方式来简单实现一下:
方式一: - (void)viewDidLoad { [super viewDidLoad]; // 开启一条线程下载图片 [NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil]; } - (void)downloadImage { // 网络图片url NSURL *url = [NSURL URLWithString:@"http://img3.imgtn.bdimg.com/it/u=3841157212,2135341815&fm=206&gp=0.jpg"]; // 根据url下载图片数据到本地 NSData *imageData = [NSData dataWithContentsOfURL:url]; // 把下载到本地的二进制数据转成图片 UIImage *image = [UIImage imageWithData:imageData]; // 回到主线程刷新UI // 第一种方式 [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES]; // 第二种方式 // 直接调用iconView里面的setImage:方法就可以实现刷新 // [self.iconView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES]; // 第三种方式 // 此方法可以方便自由在主线程和其它线程切换 // [self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES]; } - (void)showImage:(UIImage *)image { self.iconView.image = image; }1.先来看看异步并发队列
- (void)test { /** * 参数一:C语言的字符串,给队列起一个名字或标识 * 参数二:队列类型 DISPATCH_QUEUE_CONCURRENT 并发 DISPATCH_QUEUE_SERIAL 串行 */ dispatch_queue_t queue = dispatch_queue_create("并发队列", DISPATCH_QUEUE_CONCURRENT); /** * 使用函数封装任务 * 参数一:获取队列 * 参数二:需要执行的任务 */ dispatch_async(queue, ^{ NSLog(@"在:%@线程执行了任务",[NSThread currentThread]); }); NSLog(@"结束"); }执行结果:
2.再来看看同步并发队列
- (void)test { /** * 参数一:C语言的字符串,给队列起一个名字或标识 * 参数二:队列类型 DISPATCH_QUEUE_CONCURRENT 并发 DISPATCH_QUEUE_SERIAL 串行(串行队列可以用NULL表示) */ dispatch_queue_t queue = dispatch_queue_create("并发队列", DISPATCH_QUEUE_CONCURRENT); /** * 使用函数封装任务 * 参数一:获取队列 * 参数二:需要执行的任务 */ dispatch_sync(queue, ^{ NSLog(@"在:%@线程执行了任务",[NSThread currentThread]); }); NSLog(@"结束"); }执行结果:
1.同步函数+并发队列
dispatch_queue_t queue = dispatch_queue_create("并发队列", DISPATCH_QUEUE_CONCURRENT); dispatch_sync(queue, ^{ NSLog(@"当前线程:%@",[NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"当前线程:%@",[NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"当前线程:%@",[NSThread currentThread]); });执行结果:同步函数+并发队列没有开启子线程的能力
2.异步函数+并发队列
- (void)test2 { dispatch_queue_t queue = dispatch_queue_create("并发队列", DISPATCH_QUEUE_CONCURRENT); dispatch_async(queue, ^{ NSLog(@"当前线程:%@",[NSThread currentThread]); }); dispatch_async(queue, ^{ NSLog(@"当前线程:%@",[NSThread currentThread]); }); dispatch_async(queue, ^{ NSLog(@"当前线程:%@",[NSThread currentThread]); }); }执行结果:异步函数+并发队列会自动开启3条子线程执行任务
从上面可以看出,异步函数拥有开启子线程的能力,而同步函数没有开启子线程的能力。
1.同步函数+串行队列
- (void)test2 { dispatch_queue_t queue = dispatch_queue_create("串行队列", DISPATCH_QUEUE_SERIAL); dispatch_sync(queue, ^{ NSLog(@"当前线程:%@",[NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"当前线程:%@",[NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"当前线程:%@",[NSThread currentThread]); }); }执行结果:进一步证明同步函数没有开启子线程的能力,他的所有任务都在主线程中执行
2.异步函数+串行队列
- (void)test2 { dispatch_queue_t queue = dispatch_queue_create("串行队列", DISPATCH_QUEUE_SERIAL); dispatch_async(queue, ^{ NSLog(@"当前线程:%@",[NSThread currentThread]); }); dispatch_async(queue, ^{ NSLog(@"当前线程:%@",[NSThread currentThread]); }); dispatch_async(queue, ^{ NSLog(@"当前线程:%@",[NSThread currentThread]); }); }执行结果:开启了一条子线程,在子线程中依次执行任务
1.在同步函数+串行队列中,任务依旧是在主线程中执行。
2.在异步函数+串行队列中,会自动开启一条子线程,在子线程中依次执行任务
3.再一次证明同步函数没有开启子线程的能力
执行结果:在结果中我们看到GCD创建了6条线程,但是实际上GCD创建多少条线程完全由系统当前情况而定,我们是无法控制的。
1.主队列+异步函数
- (void)test4 { // 获取主队列 dispatch_queue_t queue = dispatch_get_main_queue(); // 添加任务 dispatch_async(queue, ^{ NSLog(@"当前线程:%@", [NSThread currentThread]); }); dispatch_async(queue, ^{ NSLog(@"当前线程:%@", [NSThread currentThread]); }); dispatch_async(queue, ^{ NSLog(@"当前线程:%@", [NSThread currentThread]); }); }执行结果:任务都在主线程中执行
2.同步函数+主队列
- (void)test4 { // 获取主队列 dispatch_queue_t queue = dispatch_get_main_queue(); // 添加任务 dispatch_sync(queue, ^{ NSLog(@"当前线程:%@", [NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"当前线程:%@", [NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"当前线程:%@", [NSThread currentThread]); }); }执行结果: 进入死锁状态,因为主队列执行任务的时候,在调度任务的时候,会先调用主线程的状态,如果当前有任务在做,则会等待主线程执行完任务再执行自己的任务
执行结果:
使用sync函数往当前串行队列中添加任务,会卡主当前的串行队列。
执行结果:
执行结果:
执行结果:
执行结果:
在GCD中,为我们提供了一个迭代函数,可以开启子线程快速进行遍历,这样就可以大大提高效率,而且使用非常简单。接下来使用迭代函数来进行文件复制的操作: - (void)test9 { // 获得文件原始路径(上层文件夹得路径) NSString *fromPath = @"/Users/yeshaojian/Desktop/test"; // 获得文件的目标路径 NSString *toPath = @"/Users/yeshaojian/Desktop/test2"; // 得到文件路径下面的所有文件 NSArray *subpaths = [[NSFileManager defaultManager] subpathsAtPath:fromPath]; NSLog(@"文件名:%@",subpaths); // 获取数组中文件的个数 NSInteger count = subpaths.count; // 将要迭代的操作放到迭代函数内 dispatch_apply(count, dispatch_get_global_queue(0, 0), ^(size_t index){ // 拼接需要复制的文件的全路径 NSString *fromFullpath = [fromPath stringByAppendingPathComponent:subpaths[index]]; // 拼接目标目录的全路径 NSString *toFullpath = [toPath stringByAppendingPathComponent:subpaths[index]]; // 执行文件剪切操作 /* * 参数一:文件在哪里的全路径 * 参数二:文件要被剪切到哪里的全路径 */ [[NSFileManager defaultManager] moveItemAtPath:fromFullpath toPath:toFullpath error:nil]; NSLog(@"拼接需要复制的文件的全路径:%@ -- 拼接目标目录的全路径:%@ -- 当前线程:%@",fromFullpath,toFullpath,[NSThread currentThread]); }); }执行结果:
1.队列组的基本使用
- (void)test10 { // 获取队列组,用来管理队列 dispatch_group_t group = dispatch_group_create(); // 获取并发队列 dispatch_queue_t queue = dispatch_queue_create("cs", DISPATCH_QUEUE_CONCURRENT); // 添加任务 dispatch_group_async(group, queue, ^{ NSLog(@"cs1---%@", [NSThread currentThread]); }); dispatch_group_async(group, queue, ^{ NSLog(@"cs2---%@", [NSThread currentThread]); }); dispatch_group_async(group, queue, ^{ NSLog(@"cs3---%@", [NSThread currentThread]); }); // 拦截通知:当队列组中所有的任务都执行完毕后,会调用下面方法的block块 dispatch_group_notify(group, queue, ^{ NSLog(@"完成"); }); }执行结果:
拓展: 在一些框架或者早期项目中,可能会见到下面2种队列组的使用方法,在这边顺带提及一下,但不推荐使用,因为太过繁琐。
第一种
- (void)test11 { // 获得队列组,管理队列 dispatch_group_t group = dispatch_group_create(); // 获得并发队列 dispatch_queue_t queue = dispatch_queue_create("download", DISPATCH_QUEUE_CONCURRENT); // 表示开始把后面的异步任务纳入到监听范围 //dispatch_group_enter & dispatch_group_leave dispatch_group_enter(group); // 使用异步函数封装任务 dispatch_async(queue, ^{ NSLog(@"1---%@",[NSThread currentThread]); // 通知队列组该任务已经执行完毕 dispatch_group_leave(group); }); dispatch_group_enter(group); dispatch_async(queue, ^{ NSLog(@"2---%@",[NSThread currentThread]); dispatch_group_leave(group); }); dispatch_group_enter(group); dispatch_async(queue, ^{ NSLog(@"3---%@",[NSThread currentThread]); dispatch_group_leave(group); }); // 拦截通知 dispatch_group_notify(group, queue, ^{ NSLog(@"--完成---"); }); }第二种
- (void)test11 { // 获得队列组,管理队列 dispatch_group_t group = dispatch_group_create(); // 获得并发队列 dispatch_queue_t queue = dispatch_queue_create("download", DISPATCH_QUEUE_CONCURRENT); // 表示开始把后面的异步任务纳入到监听范围 //dispatch_group_enter & dispatch_group_leave dispatch_group_enter(group); // 使用异步函数封装任务 dispatch_async(queue, ^{ NSLog(@"1---%@",[NSThread currentThread]); // 通知队列组该任务已经执行完毕 dispatch_group_leave(group); }); dispatch_group_enter(group); dispatch_async(queue, ^{ NSLog(@"2---%@",[NSThread currentThread]); dispatch_group_leave(group); }); dispatch_group_enter(group); dispatch_async(queue, ^{ NSLog(@"3---%@",[NSThread currentThread]); dispatch_group_leave(group); }); // 等待DISPATCH_TIME_FOREVER 死等,一直要等到所有的任务都执行完毕之后才会继续往下执行 // 同步执行 dispatch_time_t timer = dispatch_time(DISPATCH_TIME_NOW, 0.00001 * NSEC_PER_SEC); // 等待timer m的时间 不管队列中的任务有没有执行完毕都继续往下执行,如果在该时间内所有事任务都执行完毕了那么会返回一个0,否则是非0值 long n = dispatch_group_wait(group, timer); NSLog(@"%ld",n); NSLog(@"--完成---"); }1.异步函数(创建一个使用函数封装代码的异步函数)
- (void)test12 { /** * 参数一:队列 * 参数二:要传给函数的参数 * 参数三:函数 */ dispatch_async_f(dispatch_get_global_queue(0, 0), NULL, testTask); } void testTask(void *param) { NSLog(@"%@", [NSThread currentThread]); }2.同步函数(创建一个使用函数封装代码的同步函数)
- (void)test12 { /** * 参数一:队列 * 参数二:要传给函数的参数 * 参数三:函数 */ dispatch_sync_f(dispatch_get_global_queue(0, 0), NULL, testTask); } void testTask(void *param) { NSLog(@"%@", [NSThread currentThread]); } 上面使用的是函数来封装要处理的代码,使用比较不方便,且block是轻量级的数据结构,更推荐使用block封装代码的形式创建同步\异步函数。执行结果:需要和队列并用才会开启子线程执行任务
第二种方式 —— Block - (void)blockTest { NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"下载:%@",[NSThread currentThread]); }]; NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"下载:%@",[NSThread currentThread]); }]; NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"下载:%@",[NSThread currentThread]); }]; [op1 addExecutionBlock:^{ NSLog(@"增加的下载:%@", [NSThread currentThread]); }]; // 开启任务 [op1 start]; [op2 start]; [op3 start]; } - (void)download { NSLog(@"下载:%@",[NSThread currentThread]); }执行结果:如果一条线程中执行的操作大于1就会开启新线程并发执行
方式三 —— 自定义NSOperation1.先创建一个继承自NSOperation的类并重写main方法
- (void)main { NSLog(@"当前线程:%@", [NSThread currentThread]); }2.在需要使用的类中引用自定义的类,并创建开启任务
- (void)custom { SJOperation *op1 = [[SJOperation alloc] init]; [op1 start]; }执行结果:需要手动开启线程或者与队列并用才会开启子线程
执行结果:所有任务都在主队列中执行,且是串行队列
非主队列(获取方式:alloc init) 同时具备并发和串行功能默认下是并发的 - (void)invocationQueue { 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]; // 获取非主队列 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperation:op1]; [queue addOperation:op2]; [queue addOperation:op3]; }执行结果:所有任务在子线程中并发执行
执行结果:所有任务都在子线程中并发执行
1.串行队列示例
- (void)blockQueue { // 创建非主队列 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; // 设置最大并发数为1,则队列为串行队列 queue.maxConcurrentOperationCount = 1; [queue addOperationWithBlock:^{ NSLog(@"下载1:%@",[NSThread currentThread]); }]; [queue addOperationWithBlock:^{ NSLog(@"下载2:%@",[NSThread currentThread]); }]; [queue addOperationWithBlock:^{ NSLog(@"下载3:%@",[NSThread currentThread]); }]; }执行结果:按照任务添加顺序执行,所以是串行队列
2.并发队列示例
- (void)blockQueue { // 创建非主队列 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; // 设置最大并发数为6,一般子线程控制在6以内,太多线程会使设备压力过大 queue.maxConcurrentOperationCount = 6; [queue addOperationWithBlock:^{ NSLog(@"下载1:%@",[NSThread currentThread]); }]; [queue addOperationWithBlock:^{ NSLog(@"下载2:%@",[NSThread currentThread]); }]; [queue addOperationWithBlock:^{ NSLog(@"下载3:%@",[NSThread currentThread]); }]; }执行结果:程序并没有按照添加顺序完成任务,所以是并发执行
#### 注意:
一般子线程控制在6以内,太多线程会使设备压力过大maxConcurrentOperationCount默认值为-1(在计算机中,-1一般指最大值)如果将maxConcurrentOperationCount设置为0,说明同一时间内执行0个任务,所以任务将不会执行。1.暂停
// 暂停 [queue setSuspended:YES];2.恢复
// 取消 [queue setSuspended:NO];3.取消
// 取消队列中所有操作,且取消后的任务不可恢复 [queue cancelAllOperations];1.队列中的的任务是有状态的,分别是 —— 等待;执行;完成三种状态,且暂停、恢复和取消操作并不能作用于当前正处于执行状态的任务,只能作用于等待状态的任务。 2.如果是自定义的NSOperation,会发现暂停、恢复操作对其无效,对于这种情况,可以用以下方式解决 —— 使用取消操作
- (void)main { // 模拟耗时操作 for (int i = 0; i< 200; i++) { NSLog(@"1当前线程:%@", [NSThread currentThread]); } // 判断当前状态,如果已经取消,直接返回 if (self.cancelled) return; // 模拟耗时操作 for (int i = 0; i< 200; i++) { NSLog(@"2当前线程:%@", [NSThread currentThread]); } // 判断当前状态,如果已经取消,直接返回 if (self.cancelled) return; // 模拟耗时操作 for (int i = 0; i< 200; i++) { NSLog(@"3当前线程:%@", [NSThread currentThread]); } // 判断当前状态,如果已经取消,直接返回 if (self.cancelled) return; }解决问题思路:其实这是苹果官方文档中的建议 —— 因为,当我们调用cancelAllOperations:方法的时候,他内部的cancelled属性就会为真,每执行完一个耗时操作后都进行一次判断,如果发现已经取消,则退出执行。如果想更精确操控的话,也可以将判断操作放到耗时操作中,但是不建议这样做,因为这样性能极差。
执行结果:先执行完op3,等op3执行完成后才执行op2,当op2执行完毕后,才执行op1
执行结果:
在开发中最常用的就是GCD和NSOperation来进行多线程开发,NSThread更多是在测试时辅助使用,pthread则很少看见,这里为大家简单整理一下他们之间的区别
GCD和NSOperation的对比 GCD是纯C语言的API,而操作队列(NSOperation)则是Object-C的对象在GCD中,任务用Block块来表示,而块是轻量级的数据结构,相反,操作队列(NSOperation)中的操作NSOperation是比较重量级的Object-C对象那么在开发中如何选择呢? 一般如果任务之间有依赖关系或者需要监听任务执行的过程(KVO),首选NSOperation单纯进行一些耗时操作则选用GCD,因为相比NSOperation,GCD效率更高,性能更好NSOperation和NSOperationQueue好处 NSOperation可以方便设置操作优先级(表示操作在队列中与其它操作之间的优先关系,级别越高越先执行)NSOperation可以通过KVO的方式对NSOperation对象进行监听控制(监听当前操作是处于完成,取消还是执行状态)NSOperation可以方便设置操作之间的依赖关系通过自定义NSOperation子类可以实现操作复用转载于:https://www.cnblogs.com/miaomiaoshen/p/5419008.html
相关资源:各显卡算力对照表!