同步线程说的是对多个并发线程同步
NSLock 方式
NSLock *lock = [[NSLock alloc]init];
[lock lock];
[obj yourMethod];
[lock unlock];
@synchronized(){
[obj yourMethod];
}
以上的代码[obj yourMethod];是关键的代码每次只能被一个线程调用。
以下是使用的实例:
- (void)viewDidLoad {
[super viewDidLoad];
//默认有10张票
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) {
//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)sellTickets
{
while (1) {
@synchronized(self){ //只能加一把锁