iOS 多线程 - NSThread
来源:互联网 发布:如果做app社交软件 编辑:程序博客网 时间:2024/05/03 13:03
主线程要负责UI和响应事件,不能受复杂任务拖慢,需要使用多线程。
多线程编程方法:
1.Thread :是三种方法里面相对轻量级的,但需要管理线程的生命周期、同步、加锁问题,这会导致一定的性能开销
2.NSOperation:以面向对象的方式封装了需要执行的操作,不必关心线程管理、同步等问题。NSOperation是一个抽象基类,iOS提供了两种默认实现:NSInvocationOperation和NSBlockOperation,当然也可以自定义NSOperation
3.GCD:提供了一些新特性、运行库来支持多核并行编程,在多个cpu上提升效率
一、使用步骤
1.创建线程的方法
//实例方法 NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(run) object:nil]; [thread start]; //类方法 [NSThreaddetachNewThreadSelector:@selector(run2) toTarget:selfwithObject:nil]; //隐式创建方法 [selfperformSelectorInBackground:@selector(run3) withObject:nil];
二、基本属性
1.常用属性设置
//设置线程的优先级(0,-1,1最高级) thread.threadPriority = 1; //获取当前线程 NSThread *thread = [NSThread currentThread]; //获取主线程 NSThread *thread = [NSThread mainThread]; //暂停当前线程 [NSThreadsleepForTimeInterval:2]; NSDate *date = [NSDatedateWithTimeInterval:2sinceDate:[NSDatedate]]; [NSThreadsleepUntilDate:date];
2.线程间通信
1个线程传递数据给另1个线程,在1个线程中执行完特定任务后,转到另1个线程继续执行任务。
//线程间的通信 //在指定线程上执行操作 [selfperformSelector:@selector(run) onThread:thread withObject:nilwaitUntilDone:YES]; //在主线程上执行操作 [selfperformSelectorOnMainThread:@selector(run) withObject:nilwaitUntilDone:YES]; //在当前线程执行操作 [selfperformSelector:@selector(run) withObject:nil];
3.线程同步/互斥锁使用格式
//加锁方法一,使用条件锁 [_ticketsConditionlock]; if (_tickets >= 0 ) { [NSThreadsleepForTimeInterval:0.09]; _count = 100 - _tickets; NSLog(@"当前票数是%d,售出%d,线程名%@",_tickets,_count,[[NSThreadcurrentThread] name]); _tickets--; } else { break; } [_ticketsConditionunlock]; //加锁方法二,使用NSLock对象 [_theLocklock]; if (_tickets >= 0 ) { [NSThreadsleepForTimeInterval:0.09]; _count = 100 - _tickets; NSLog(@"当前票数是%d,售出%d,线程名%@",_tickets,_count,[[NSThreadcurrentThread] name]); _tickets--; } else { break; } [_theLockunlock]; //加锁方法三,使用@synchronize,只能加一把锁,多把是无效的 @synchronized(self) { if (_tickets >= 0 ) { [NSThreadsleepForTimeInterval:0.09]; _count = 100 - _tickets; NSLog(@"当前票数是%d,售出%d,线程名%@",_tickets,_count,[[NSThreadcurrentThread] name]); _tickets--; } else { break; } }
三、代码示例
1.创建线程、互斥锁使用、线程间通信示例
https://github.com/shileseal/SLNSThreadDemo
四、总结
2 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
- 压力很大
- iOS 数据存储 - Core Data
- 执行oracle的存储过程
- 推荐Android Studio上的几个插件
- 短工邦技术部成员简介
- iOS 多线程 - NSThread
- 获取NSString的尺寸
- Error“Cannot change version of project facet Dynamic web module to 2.5”导致Tomcat无法启动解决办法
- VS2010 编译64位Qt
- 一天一点xib:7再聊SB
- Windbg条件断点之字符串比较
- Unity3D学习笔记(三)为地形添加花草树木
- Matlab实现图片格式转换 pgm转jpg等
- edittext_selector&button_selector