NSThread
创建线程
// 第一种方法
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"jack"];
//启动线程
[thread start];
//第二种方法
[self performSelectorInBackground:@selector(run:) withObject:@"jack"];
//第三种方法
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"rose"];
//执行方法
- (void)run:(NSString *)param
{
for (NSInteger i = 0; i<100; i++) {
NSLog(@"-----run-----%@--%@", param, [NSThread currentThread]);
}
}
线程的状态
控制线程状态
- 启动线程
- (void)start;
// 进入就绪状态 -> 运行状态。当线程任务执行完毕,自动进入死亡状态
- 阻塞(暂停)线程
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
// 进入阻塞状态
- 强制停止线程
+ (void)exit;
// 进入死亡状态
// 注意:一旦线程停止(死亡)了,就不能再次开启任务
多线程的安全隐患
资源共享
(1)1块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源
(2)比如多个线程访问同一个对象、同一个变量、同一个文件当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题
安全隐患的解决 - 互斥锁
- 互斥锁使用格式
@synchronized(锁对象) { // 需要锁定的代码 }
注意:锁定1份代码只用1把锁,用多把锁是无效的
- 示例代码
//创建3条线程
/** 售票员01 */
@property (nonatomic, strong) NSThread *thread01;
/** 售票员02 */
@property (nonatomic, strong) NSThread *thread02;
/** 售票员03 */
@property (nonatomic, strong) NSThread *thread03;
/** 票的总数 */
@property (nonatomic, assign) NSInteger ticketCount;
//添加线程方法
self.ticketCount = 100;
self.thread01 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread01.name = @"售票员01";
self.thread02 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread02.name = @"售票员02";
self.thread03 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread03.name = @"售票员03";
//线程运行
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.thread01 start];
[self.thread02 start];
[self.thread03 start];
}
//方法打印 加锁实例
- (void)saleTicket
{
while (1) {
@synchronized(self) {
// 先取出总数
NSInteger count = self.ticketCount;
if (count > 0) {
self.ticketCount = count - 1;
NSLog(@"%@卖了一张票,还剩下%zd张", [NSThread currentThread].name, self.ticketCount);
} else {
NSLog(@"票已经卖完了");
break;
}
}
}
}
互斥锁的优缺点
优点:能有效防止因多线程抢夺资源造成的数据安全问题
缺点:需要消耗大量的CPU资源互斥锁的使用前提:多条线程抢夺同一块资源
相关专业术语:线程同步
线程同步的意思是:多条线程在同一条线上执行(按顺序地执行任务)
互斥锁,就是使用了线程同步技术
原子和非原子属性的选择
nonatomic和atomic对比
atomic:线程安全,需要消耗大量的资源
nonatomic:非线程安全,适合内存小的移动设备iOS开发的建议
所有属性都声明为nonatomic
尽量避免多线程抢夺同一块资源
尽量将加锁、资源抢夺的业务逻辑交给服务器端处理,减小移动客户端的压力
线程间通信方式
- performSelector方法
//开线程 执行下载任务
[self performSelectorInBackground:@selector(download3) withObject:nil];
// 回到主线程,显示图片
[self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
[self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
[self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];
//注意: waitUntilDone 表示是否等待任务完成再继续执行
- NSPort NSMessagePort NSMachPort 方法