1.在主线程执行多次NSLog模拟耗时操作

结果,卡住主线程

解决方案: performSelectorInBackground让程序在后台执行
2.pthread的使用
开辟子线程,执行一个函数
__bridge桥接,OC对象和C指针之间的转换
{  /*参数1:线程的编号(地址)参数2:线程的属性 NULL nil(oc)参数3:要调用的函数 void *  (*)  (void *)参数4:给要调用的函数传递的参数*///开辟新的线程
    pthread_t ID;NSString *str = @"ls";//__bridge桥接 类型转换(oc - 》c)//MRC 谁创建,谁释放//ARC 自动管理int result = pthread_create(&ID, NULL, demo, (__bridge void *)(str));//result 0 代表成功 其他代表失败if (result == 0) {NSLog(@"成功");}else{NSLog(@"失败");}}
/**pthread调用的函数*/
void * demo(void * param)
{NSString *Str = (__bridge NSString *)(param);//获取当前的代码执行在哪个线程当中,获取当前线程NSLog(@"%@ %@",Str,[NSThread currentThread]);return NULL;
}

3.NSThread的3种使用方式

{   //创建NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(demo) object:nil];//调用
    [thread start];//    //方式2
    [NSThread detachNewThreadSelector:@selector(demo) toTarget:self withObject:nil];//方式3
    [self performSelectorInBackground:@selector(demo) withObject:nil];//传递参数[self performSelectorInBackground:@selector(demo2:) withObject:@"HM"];}
- (void)demo2:(NSString *)str
{NSLog(@"%@ %@",str,[NSThread currentThread]);
}
/**要调用的方法*/
- (void)demo
{NSLog(@"%@",[NSThread currentThread]);
}

4.线程的生命周期

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{//新建状态NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(demo) object:nil];//就绪状态
    [thread start];//运行状态:系统控制的
    }
- (void)demo
{for (int i = 0; i <20; i++) {if (i == 5) {//阻塞状态//让当前的线程睡一段时间[NSThread sleepForTimeInterval:3];}else if (i == 10){//死亡状态
            [NSThread exit];}NSLog(@"%d",i);}
}

5.NSThread的属性,可以设置属性的名称、优先级

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{//线程属性//主线程占用的内存空间NSLog(@"%zd",[NSThread currentThread].stackSize/1024);//创建线程1NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(demo) object:nil];//设置线程名称thread.name = @"t1";//设置线程的优先级 参数的取值范围 0-1  0是优先级最低的,1是优先级最高 默认的是0.5[thread setThreadPriority:1.0];[thread start];//创建线程2NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(demo) object:nil];//设置线程名称thread2.name = @"t2";[thread2 setThreadPriority:0.0];[thread2 start];//设置线程的优先级不能绝对保证线程优先执行,但是线程被调用的概率提高

}
- (void)demo
{//子线程占用的内存空间NSLog(@"demo  %zd",[NSThread currentThread].stackSize/1024);
//    NSLog(@"%@",[NSThread currentThread]);for (int i = 0; i < 10; i++) {NSLog(@"%d %@",i,[NSThread currentThread].name);}}

6.线程间资源抢夺的时候,需要加互斥锁(锁住一个对象)

#import "ViewController.h"@interface ViewController ()
//总票数
@property(nonatomic,assign)int totalTickets;
@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];//设置票数为20self.totalTickets = 20;}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{//窗口1 模拟卖票NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];thread.name = @"t1";[thread start];//窗口2 模拟卖票
    NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];thread2.name = @"t2";[thread2 start];
}
/**卖票*/
- (void)sellTickets
{while (YES) {//被加锁的对象
        @synchronized(self) {//查询剩余的票数,判断if (self.totalTickets > 0) {self.totalTickets = self.totalTickets - 1;NSLog(@"剩余%d票 %@",self.totalTickets,[NSThread currentThread].name);}else{NSLog(@"票卖完了,回不了家,走路回家");break;}}}
}

7.异步下载图片,在子线程下载图片,在主线程更新UI

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{//网络图片下载/*1.不能把耗时操作放到主线程中,开辟新的线程2.刷新ui一定要在主线程
//     http://g.hiphotos.baidu.com/image/pic/item/f31fbe096b63f624cd2991e98344ebf81b4ca3e0.jpg*/NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(downloadImg) object:nil];[thread start];}
/**下载图片*/
- (void)downloadImg
{NSLog(@"downloadImg %@",[NSThread currentThread]);//获取链接地址NSURL *url = [NSURL URLWithString:@"http://g.hiphotos.baidu.com/image/pic/item/f31fbe096b63f624cd2991e98344ebf81b4ca3e0.jpg"];//转化NSData类型NSData *data = [NSData dataWithContentsOfURL:url];//转化成UIImageUIImage *img = [UIImage imageWithData:data];/*参数1:主线程要调用的方法参数2:给调用的方法传递的参数参数3:是否等待当前代码执行完毕再来执行下面的代码*/[self performSelectorOnMainThread:@selector(updataUI:) withObject:img waitUntilDone:YES];NSLog(@"end");}
/**刷新ui ui刷新必须放到主线程里面*/
- (void)updataUI:(UIImage *)img
{NSLog(@"updataUI %@",[NSThread currentThread]);[NSThread sleepForTimeInterval:3];self.HMImageView.image = img;
}

转载于:https://www.cnblogs.com/fanglove/p/5215180.html

1.多线程-NSThread相关推荐

  1. [Cocoa]深入浅出Cocoa之多线程NSThread

    深入浅出Cocoa之多线程NSThread 罗朝辉 (http://www.cnblogs.com/kesalin/) 本文遵循"署名-非商业用途-保持一致"创作公用协议 iOS ...

  2. 多线程——NSThread、GCD、NSOperation

    1.前言: 一个应用程序就是一个进程,一个进程至少包含一个线程,程序启动会自动创建一个主线程,负责UI界面的现实和控件事件的监控.多线程可以更充分的利用系统CPU资源,一定程度上提升程序的性能.1个进 ...

  3. 浅谈多线程——NSThread

    上一篇文章中我们大致了解了GCD的模式和方法,在iOS开发中除了GCD之外,还有NSThread和NSOperation两种多线程方式. 1.NSThread - a - 使用NSThread开辟多线 ...

  4. iOS学习6_多线程NSThread和GCD

    NSThread 1.显式创建线程调用start开启 NSThread * thread = [[NSThread alloc]initWithTarget:self selector:@select ...

  5. iOS多线程全套:线程生命周期,多线程的四种解决方案,线程安全问题,GCD的使用,NSOperation的使用(上)

    2017-07-08 remember17 Cocoa开发者社区 目的 本文主要是分享iOS多线程的相关内容,为了更系统的讲解,将分为以下7个方面来展开描述. 多线程的基本概念 线程的状态与生命周期 ...

  6. iOS_多线程(一)

    在学习多线程之前首先搞清楚以下几个问题. 并发:在同一时刻,只有一条指令被执行,多条指令进行快速切换执行. 并行:在同一时刻,多个处理器可以处理多条指令 1.什么是进程? 一个运行的程序就是一个进程或 ...

  7. IOS多线程开发详解

    概览 大家都知道,在开发过程中应该尽可能减少用户等待时间,让程序尽可能快的完成运算.可是无论是哪种语言开发的程序最终往往转换成汇编语言进而解释成机器码来执行.但是机器码是按顺序执行的,一个复杂的多步操 ...

  8. iOS开发系列--并行开发其实很容易

    --多线程开发 概览 大家都知道,在开发过程中应该尽可能减少用户等待时间,让程序尽可能快的完成运算.可是无论是哪种语言开发的程序最终往往转换成汇编语言进而解释成机器码来执行.但是机器码是按顺序执行的, ...

  9. [Cocoa]深入浅出Cocoa系列

    深入浅出Cocoa系列 罗朝辉 (http://www.cnblogs.com/kesalin/) 本文遵循"署名-非商业用途-保持一致"创作公用协议 这是本人在研究 Cocoa  ...

最新文章

  1. 用pandas.dataframe 的append()方法时候,合成的整个数据的索引是分块的
  2. mysql yn 字段类型_mysql常用数据类型
  3. DCMTK:OFtuple的单元测试
  4. Error:Could not resolve all files for configuration ':app:preDebugCompileClasspath'. Could not fin
  5. C#和NewSQL更配 —— TiDB入门
  6. 哇、、、、C++ 实现单向链表
  7. vim 删除当前词_vim 可视话模式(即删除一列和多列)
  8. Centos7下yum安装MySQL 5.7
  9. redis分布式锁简单总结
  10. Mapx自带的工具的理解
  11. Manjaro安装scrt8.3 201912
  12. 史陶比尔机器人CS9控制器及SP2示教器使用简易指南
  13. 压摆率和上升时间的区别
  14. Redis高频面试题(欢迎来学习讨论)
  15. Android打开系统设置界面
  16. 运动耳机怎么选,盘点目前适合运动的几款耳机
  17. 大学计算机李凤霞课本百度云,北京理工大学李凤霞老师个人资料
  18. 大数据----2.基础环境搭建
  19. Java监听mysql的binlog详解(mysql-binlog-connector)
  20. CentOS7.9通过RealVNC实现多人使用服务器桌面

热门文章

  1. python怎么安装myqr模块-python二维码操作:对QRCode和MyQR入门详解
  2. python编程语法-Python编程入门——基础语法详解(经典)
  3. 学python工资高吗-我程序员年薪 80 万被亲戚鄙视不如在二本教书的博士生?
  4. python3.7和3.8的区别-Python 3.8 新功能来一波(大部分人都不知道)
  5. python与php8-别再盲目学 Python 了!
  6. python语法大全-总结了Python中的22个基本语法
  7. python 贴吧自动回复机-python_库学习_02_微信自动回复机器人
  8. python操作excel-python操作excel
  9. python单词大全-学Python必须背的42个常见单词
  10. python报班大概多少钱-python培训班价格大概多少?