多线程
主线程 == UI线程
线程:是进程的基本执行单元.
一个进程包含一个或多个线程
同步执行:顺序执行
异步执行:同时无序执行
进程:正在运行的一个应用程序就是进程
多线程执行原理:高速切换执行,假象"同时执行"
多线程执行特征:
优点: 提高程序执行效率
缺点:线程并不是越多越好,占用cpu内存管理,
导致系统运行缓慢
缺点5:多个线程共同访问同一个变量,(共享变量)存在数据冲突
可移植操作系统Protable Operating System Interface 简称POS
NSThread 要管理生命周期
GCD 常用 OC 不要管理生命周期
NSOperation 常用 OC
对象方法创建
优点:可以设置属性,
缺点:需要手动start
类方法 创建 ->分离出一个线程
隐式 创建
类方法和隐式创建
优点:简单创建,缺点:不可以进行详细设置
周期:
新建-start>就绪->运行--切换其他线程->本线程就绪->运行-sleep>阻塞-dead>释放
就绪-> start-> 可调度线程池
// 互斥锁的格式,小括号内锁对象,任意对象,默认对象中都有一把锁,并且锁是开着的
// NSObject *obj = [[NSObject alloc] init];
// 使用锁的方式,一定会有性能的损失,因为线程会等待
网络请求info.plist文件需要添加如下文件:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key><true/>
</dict>
2016-01-24 23:35:22.420 下载图片[828:21621] This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.
报警指示UI操作应该在主线程而不应该在子线程
[self performSelectorOnMainThread:@selector(updateUIimage:) withObject:image waitUntilDone:NO];// 没有延迟
// self.myImageView.image = image;// 有延迟
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"begin");
[self demo02];// 属于子线程
NSLog(@"over");
}
-(void)demo02
{
// 创建
NSThread * thread = [[NSThread alloc]initWithTarget:self selector:@selector(myTask) object:nil];
// 创建需要开启
[thread start];
}
-(void)myTask
{
2016-01-24 11:29:19.663 多线程[37863:3930036] begin
2016-01-24 11:29:19.664 多线程[37863:3930036] over
2016-01-24 11:29:19.664 多线程[37863:3930158] <NSThread: 0x7fd63371d080>{number = 2, name = (null)}