接下来主要讲一下线程的创建和线程的安全问题
一、线程的创建(NSThread)
NSThread创建线程比较简单,主要有下面三种方式创建。
第一种
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument
第二种
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg
第三种
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;
实践一
- (void)create_thread_first{
NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"create_thread_first"];
thread.name = @"线程名字";
[thread start];
}
- (void)download:(NSString *)url{
// [NSThread sleepForTimeInterval:5];//休眠五秒
//
// NSDate * date = [NSDate dateWithTimeIntervalSinceNow:3];//休眠3秒
// [NSThread sleepUntilDate:date];
NSLog(@"%@--%@",url,[NSThread currentThread]);
}
实践一输出
实践二
- (void)create_thread_second{
[self performSelectorInBackground:@selector(download:) withObject:@"create_thread_second"];
}
实践二输出
实践三
- (void)create_thread_third{
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"create_thread_third"];
}
实践三输出
二、线程安全
但凡涉及到这个问题,一般都是一个资源被多个线程共同访问,比如多个网点卖同一种类型的电影票,但电影票的总数一定,那么我们怎么才能控制多个网点共同访问电影票的问题呢——加锁,加锁便保证了线程安全。
- (void)thread_safety{
self.leftCount = 50;
self.threadOne = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.threadOne.name = @"threadOne";
self.threadTwo = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.threadTwo.name = @"threadTwo";
self.threadThree = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.threadThree.name = @"threadThree";
[self.threadOne start];
[self.threadTwo start];
[self.threadThree start];
}
- (void)saleTicket{
while (1) {
@synchronized(self) {//加锁,保证线程安全
if (self.leftCount > 0) {
self.leftCount --;
NSLog(@"%@卖了一张票,剩余%d张票",[NSThread currentThread].name,self.leftCount);
}else{
return;//退出线程
}
}
}
}
那么输出结果如下
上面可能只是简单的例子,我要做的是抛砖引玉。