iOS 多线程NSThread
来源:互联网 发布:腾龙信息网络工程公司 编辑:程序博客网 时间:2024/05/22 00:53
多线程,在任何一门开发语言里都会碰到,语言可能不同,但是多线程的理论知识一本一样的,,,,学习多线程都会要了解几个感念,,
1线程互斥:当多个线程访问同一块资源时,为了保证线程安全,一个线程在访问时其他线程处于等待状态,
2线程死锁:当线程访问一个资源时,如果该资源已被其他线程正在访问(自己枷锁) 如果想使用该资源,必须等其他线程解锁完毕,如果不解锁线程处于等待状态
3线程同步和线程并发:属于线程之间的关系,
4线程同步:各线程执行任务之间存在依赖关系,后一个线程的执行必须依赖前一个线程任务结束.
5线程并发:线程同时执行任务,线程执行的任务之间没有依赖关系,可能后执行者先完成任务,主线程和子线程可以线程同步,但是只有子线程能够实现并发.
网络中的同步连接和异步连接属于连接方式,请求线程不同,同步连接网络请求是有主线程处理,而异步连接有子线程处理.
在iOS中创建子线程方式有三种, nsthread nsoperation GCD
第一种 创建子线程用nsthread
NSThread detachNewThreadSelector:@selector(forfor) toTarget:self withObject:nil];第二种 创建子线程
NSThread *therad = [[NSThread alloc] initWithTarget:self selector:@selector(forfor) object:nil];
[therad start];//执行任务开始子线程
- (void)forfor:(NSString *)name { //子线程中没有自动释放池 NSLog(@"wang text1=%@ isMainThread=%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);// for (int i = 0; i < 10; i++) {// NSLog(@"%d",i);// } //定时器在主线程中能够响应对应的方法,但是在子线程中不能 //原因:主线程在uiapplaictionMain 开启了事件循环,能够及时捕获操作,及时出里,但是在子线程并没有开启事件循环. @autoreleasepool {//添加autoreleasepool因为子线程中一直alloc 没有release [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aa:) userInfo:nil repeats:YES]; //获取当前线程中的事件循环. NSRunLoop *run = [NSRunLoop currentRunLoop]; [run run];//开启循环 }}
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(forfor) object:nil]; NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(test2) object:nil];//添加到任务队列中
//队列为每一个子线程分配一个子线程,因为队列是先进先出,所以分配任务时有先后顺序,但是所有的都是同时进行先出,(线程并发)
//任务队列创建线程数量 有系统性能决定,但是能够保证所有任务均在子线程中运行
NSOperationQueue *aueue =[[NSOperationQueue alloc] init];
[aueue setMaxConcurrentOperationCount:1];//设置最大并发数
// //添加任务之间的任务关系 [operation1 addDependency:operation]; [aueue addOperation:operation]; [aueue addOperation:operation1];
- (void)test2 { NSLog(@"wang test2=%@ isMainThread=%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]); for (int i = 0; i < 5; i++) { NSLog(@"Duke is Duck"); }}
0 0
- iOS 多线程 NSThread
- IOS 多线程 NSThread
- iOS多线程 nsthread
- ios NSThread多线程
- iOS多线程开发 NSThread
- IOS 多线程 线程NSThread
- iOS多线程之NSThread
- iOS多线程开发 NSThread
- ios多线程之NSThread
- IOS 多线程 线程NSThread
- iOS多线程之NSThread
- iOS多线程之NSThread
- iOS 多线程NSThread 三
- iOS 多线程NSThread
- IOS 多线程(2) --NSThread
- iOS多线程学习---NSThread
- iOS 多线程之NSThread
- IOS多线程之NSThread
- flex widget之间的数据交互问题
- JSON详解
- python的range()函数用法
- 新增加一项技能
- 使用JavaIO技术实现文件切割与文件合并
- iOS 多线程NSThread
- STM8出现如下问题的解决方案
- 面试准备--计算机网络(二)
- js多行文本的处理方法
- Android远程服务一:android AIDL远程服务调用
- 微信公众账号 点击返回页面刷新页面得到两个相同的code导致程序报错的问题
- 暑假集训第三周第二阶段 搜索 D - 变形课
- PHP实现下载文件功能
- 背包问题九讲笔记_完全背包