NSThread相关
//创建NSThread的三种方法
//1.手动启动线程,可以拿到线程对象
- (void) createNSThread
{
/*
*NSThread *thread = [NSThread alloc]initWithTarget:(nonnull id) selector:(nonnull SEL) object:(nullable id)
* 参数一:目标对象
* 参数二:方法选择器
* 参数三:前面的方法需要传递参数
*/
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"ABC"];
[thread start];
}
//2.分离子线程,但拿不到线程对象
- (void) createNSThread2
{
/*类方法
*[NSThread detachNewThreadSelector:(nonnull SEL) toTarget:(nonnull id) withObject:(nullable id)];
* 参数一:方法选择器
* 参数二:目标对象
* 参数三:前面的方法需要传递参数
*/
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"分离子线程"];
}
//3.开启后台线程,但拿不到线程对象
- (void) createNSThread3
{
/*
*[self performSelectorInBackground:(nonnull SEL) withObject:(nullable id)];
* 参数一:方法选择器
* 参数二:前面的方法需要传递参数
*/
[self performSelectorInBackground:@selector(run:) withObject:@"开启后台线程"];
}
- (void) run:(NSString*)param
{
//param为传递来的参数
NSLog(@"----run----%@",[NSThread currentThread]);
NSLog(@"传递的参数为:%@",param);
for(long i = 0; i < 100000; i++)
{
NSLog(@"%ld",i);
}
}
设置NSThread的名称
[thread3 setName:@"thread3"];
设置NSThread的优先级,取值0.0 ~ 1.0 , 默认0.5,值越大,优先级越高
[thread3 setThreadPriority:1.0];
线程的生命周期
当线程任务执行完毕后线程对象才会被释放
启动线程
//进入就绪状态 -> 运行状态,当线程任务执行完毕,自动进入死亡状态
-(void)start;
//进入阻塞状态
+(void)sleepUntilDate:(NSDate*)date;
+(void)sleepForTimeInterval:(NSTimeInterval)ti;
//进入死亡状态,线程死亡,是无法重启的
-(void)exit;
多线程的安全隐患
资源共享,一块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源。比如多个线程访问同一个对象、同一个变量、同一个文件,当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题
//
// YYViewController.m
// 05-线程安全
//
// Created by apple on 14-6-23.
// Copyright (c) 2014年 itcase. All rights reserved.
//
#import "YYViewController.h"
@interface YYViewController ()
//剩余票数
@property(nonatomic,assign) int leftTicketsCount;
@property(nonatomic,strong)NSThread *thread1;
@property(nonatomic,strong)NSThread *thread2;
@property(nonatomic,strong)NSThread *thread3;
@end
@implementation YYViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//默认有20张票
self.leftTicketsCount=20;
//开启多个线程,模拟售票员售票
self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread1.name=@"售票员A";
self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread2.name=@"售票员B";
self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread3.name=@"售票员C";
}
-(void)sellTickets
{
while (1) {
//1.先检查票数
int count=self.leftTicketsCount;
if (count>0) {
//暂停一段时间
[NSThread sleepForTimeInterval:0.002];
//2.票数-1
self.leftTicketsCount= count-1;
//获取当前线程
NSThread *current=[NSThread currentThread];
NSLog(@"%@--卖了一张票,还剩余%d张票",current,self.leftTicketsCount);
}else
{
//退出线程
[NSThread exit];
}
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//开启线程
[self.thread1 start];
[self.thread2 start];
[self.thread3 start];
}
@end
出现3个线程同时出现相同的剩余票数
造成安全隐患的原因:
解决办法:互斥锁
互斥锁
互斥锁使用格式
@synchronized(锁对象) { // 需要锁定的代码 }
使用锁的注意事项:
- 锁必须是全局唯一的
- 注意加锁的位置
- 需要加锁的前提条件是,多线程要共享同一资源
- 加锁是要代价的,代价就是耗费性能
- 加锁的结果可以使线程达到同步,未加锁是异步的操作
注意:锁定1份代码只用1把锁,用多把锁是无效的
//
// YYViewController.m
// 05-线程安全
//
// Created by apple on 14-6-23.
// Copyright (c) 2014年 itcase. All rights reserved.
//
#import "YYViewController.h"
@interface YYViewController ()
//剩余票数
@property(nonatomic,assign) int leftTicketsCount;
@property(nonatomic,strong)NSThread *thread1;
@property(nonatomic,strong)NSThread *thread2;
@property(nonatomic,strong)NSThread *thread3;
@end
@implementation YYViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//默认有20张票
self.leftTicketsCount=10;
//开启多个线程,模拟售票员售票
self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread1.name=@"售票员A";
self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread2.name=@"售票员B";
self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread3.name=@"售票员C";
}
-(void)sellTickets
{
while (1) {
@synchronized(self){//只能加一把锁
//1.先检查票数
int count=self.leftTicketsCount;
if (count>0) {
//暂停一段时间
[NSThread sleepForTimeInterval:0.002];
//2.票数-1
self.leftTicketsCount= count-1;
//获取当前线程
NSThread *current=[NSThread currentThread];
NSLog(@"%@--卖了一张票,还剩余%d张票",current,self.leftTicketsCount);
}else
{
//退出线程
[NSThread exit];
}
}
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//开启线程
[self.thread1 start];
[self.thread2 start];
[self.thread3 start];
}
@end
原子和非原子属性
OC在定义属性时有nonatomic和atomic两种选择
atomic:原子属性,为setter方法加锁(默认就是atomic)
nonatomic:非原子属性,不会为setter方法加锁
atomic加锁原理
@property (assign, atomic) int age;
- (void)setAge:(int)age
{
@synchronized(self) {
_age = age;
}
}
原子和非原子属性的选择
nonatomic和atomic对比
atomic:线程安全,需要消耗大量的资源
nonatomic:非线程安全,适合内存小的移动设备
iOS开发的建议
所有属性都声明为nonatomic
尽量避免多线程抢夺同一块资源
尽量将加锁、资源抢夺的业务逻辑交给服务器端处理,减小移动客户端的压力
线程间通信
在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信
线程间通信的体现 1个线程传递数据给另1个线程 在1个线程中执行完特定任务后,转到另1个线程继续执行任务
线程间通信常用方法
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
一个图片下载并显示的多线程通信的应用实例:
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//下载操作属于耗时操作,可以转入子线程
[self performSelectorInBackground:@selector(download) withObject:nil];
}
- (void)download
{
NSURL *url = [[NSURL alloc] initWithString:@"http://images.cnitblog.com/i/450136/201406/241326487366534.png"];
/*
需要在info.plist开启以下权限
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
*/
NSData *data = [NSData dataWithContentsOfURL:url];
NSDate *startTime = [NSDate date];
CFTimeInterval start = CFAbsoluteTimeGetCurrent();
UIImage *image = [UIImage imageWithData:data];
NSDate *endTime = [NSDate date];
CFTimeInterval end = CFAbsoluteTimeGetCurrent();
NSLog(@"下载耗时:%f",[endTime timeIntervalSinceDate:startTime]);
NSLog(@"下载耗时:%f",end - start);
//当图片下载完毕,可以将image显示到imageView的过程放到主线程中
//参数1:回到主线程后要执行的方法
//参数2:执行方法所带的参数
//参数3:是否等待
[self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
//也可通过这样的方法回到主线程
//[self performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
}
- (void)setImage:(UIImage*)image
{
self.imageView.image = image;
}
@end
以上用到的线程跳转方法属于NSObject的一个分类(categray)NSThreadPerformAdditions中的方法,所以只要是继承与NSObject的对象都可以直接调用到
@interface NSObject (NSThreadPerformAdditions)
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
// equivalent to the first method with kCFRunLoopCommonModes
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array NS_AVAILABLE(10_5, 2_0);
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait NS_AVAILABLE(10_5, 2_0);
// equivalent to the first method with kCFRunLoopCommonModes
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg NS_AVAILABLE(10_5, 2_0);
@end
因为imageView也是继承与NSObject的,因此它直接就可以调用回到主线程的方法,并在调用的方法的参数使用自己的方法,无需再写一个方法
[self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];