1、优缺点
1.优点:NSThread比其他两种多线程方案较轻量级,更直观地控制线程对象
2.缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销
2、 NSThread相关的主要方法:
创建、启动线程
// 线程一启动,就会在线程thread中执行self的run方法
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];
创建线程后自动启动线程
[NSThread detachNewThreadSelector:@selector(test) toTarget:self withObject:nil];
隐式创建并启动线程
[self performSelectorInBackground:@selector(run) withObject:nil];
3、互斥锁
@synchronized(锁对象) { // 需要锁定的代码 }
互斥锁的优缺点
优点:能有效防止因多线程抢夺资源造成的数据安全问题
缺点:需要消耗大量的CPU资源
互斥锁的使用前提:多条线程抢夺同一块资源
4、线程间通信
线程间通信常用方法
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
5、模拟一个卖票系统
self.tickets = 100;//总共票数
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
thread1.name = @"售票机1";
[thread1 start];
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
thread2.name = @"售票机2";
[thread2 start];
- (void)run {
if (_lock == nil)
{
_lock = [[NSLock alloc] init];
}
while (YES)
{
[_lock lock];
if (_tickets > 0)
{
_tickets -= 1;
NSString *message = [NSString stringWithFormat:@"当前票数是%ld,售票线程是%@",(long)_tickets,[[NSThread currentThread] name]];
NSLog(@"message == %@",message);
[_lock unlock];
if ([[[NSThread currentThread] name] isEqualToString:@"售票机1"])
{
[NSThread sleepForTimeInterval:0.2];
}
else
[NSThread sleepForTimeInterval:0.3];
}
else
{
[_lock unlock];
break;
}
}
}