
示意圖.png
1、優(yōu)缺點(diǎn)
1.優(yōu)點(diǎn):NSThread比其他兩種多線程方案較輕量級(jí),更直觀地控制線程對(duì)象
2.缺點(diǎn):需要自己管理線程的生命周期,線程同步。線程同步對(duì)數(shù)據(jù)的加鎖會(huì)有一定的系統(tǒng)開(kāi)銷
2、 NSThread相關(guān)的主要方法:
創(chuàng)建、啟動(dòng)線程
// 線程一啟動(dòng),就會(huì)在線程thread中執(zhí)行self的run方法
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];
創(chuàng)建線程后自動(dòng)啟動(dòng)線程
[NSThread detachNewThreadSelector:@selector(test) toTarget:self withObject:nil];
隱式創(chuàng)建并啟動(dòng)線程
[self performSelectorInBackground:@selector(run) withObject:nil];
3、互斥鎖
@synchronized(鎖對(duì)象) { // 需要鎖定的代碼 }
互斥鎖的優(yōu)缺點(diǎn)
優(yōu)點(diǎn):能有效防止因多線程搶奪資源造成的數(shù)據(jù)安全問(wèn)題
缺點(diǎn):需要消耗大量的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、模擬一個(gè)賣票系統(tǒng)
self.tickets = 100;//總共票數(shù)
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
thread1.name = @"售票機(jī)1";
[thread1 start];
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
thread2.name = @"售票機(jī)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:@"當(dāng)前票數(shù)是%ld,售票線程是%@",(long)_tickets,[[NSThread currentThread] name]];
NSLog(@"message == %@",message);
[_lock unlock];
if ([[[NSThread currentThread] name] isEqualToString:@"售票機(jī)1"])
{
[NSThread sleepForTimeInterval:0.2];
}
else
[NSThread sleepForTimeInterval:0.3];
}
else
{
[_lock unlock];
break;
}
}
}